1
0
mirror of https://github.com/node-red/node-red-nodes.git synced 2023-10-10 13:36:58 +02:00

XMPP node - now with credentials. And multiple connections and

clean disconnects.
This commit is contained in:
Dave C-J 2014-05-29 18:31:36 +01:00
parent ae22efb270
commit 3691bc6294
2 changed files with 322 additions and 83 deletions

View File

@ -1,5 +1,5 @@
<!-- <!--
Copyright 2013 IBM Corp. Copyright 2013,2014 IBM Corp.
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
@ -14,12 +14,59 @@
limitations under the License. limitations under the License.
--> -->
<script type="text/x-red" data-template-name="xmpp"> <script type="text/x-red" data-template-name="xmpp in">
<div class="form-row"> <div class="form-row">
<label for="node-input-server"><i class="icon-bookmark"></i> Server</label> <label for="node-input-server"><i class="icon-bookmark"></i> Server</label>
<input type="text" id="node-input-server" placeholder="talk.google.com" style="width: 40%;" > <input type="text" id="node-input-server">
<label for="node-input-port" style="margin-left: 10px; width: 35px; "> Port</label> </div>
<input type="text" id="node-input-port" placeholder="Port" style="width:45px"> <div class="form-row">
<label for="node-input-to"><i class="icon-envelope"></i> Buddy</label>
<input type="text" id="node-input-to" placeholder="joe@gmail.com">
</div>
<div class="form-row">
<label>&nbsp;</label>
<input type="checkbox" id="node-input-join" placeholder="" style="display: inline-block; width: auto; vertical-align: top;">
<label for="node-input-join" style="width: 70%;">Is a Chat Room ?</label>
</div>
<div class="form-row">
<label for="node-input-name"><i class="icon-tag"></i> Name</label>
<input type="text" id="node-input-name" placeholder="Name">
</div>
</script>
<script type="text/x-red" data-help-name="xmpp in">
<p>Connects to an XMPP server to receive messages.</p>
<p>The <b>Buddy</b> field is the id of the buddy or room you want to receive messages from.</p>
<p>Incoming messages will appear as <b>msg.payload</b> on the first output, while <b>msg.topic</b> will contain who it is from.</p>
<p>The second output will show the presence and status of a user in <b>msg.payload</b>. Again <b>msg.topic</b> will hold the user.</p>
</script>
<script type="text/javascript">
RED.nodes.registerType('xmpp in',{
category: 'social-input',
color:"#F4F492",
defaults: {
name: {value:""},
server: {type:"xmpp-server",required:true},
to: {value:"",required:true},
join: {value:false}
},
inputs:0,
outputs:2,
icon: "xmpp.png",
label: function() {
return this.name||"xmpp";
},
labelStyle: function() {
return (this.name)?"node_label_italic":"";
}
});
</script>
<script type="text/x-red" data-template-name="xmpp out">
<div class="form-row">
<label for="node-input-server"><i class="icon-bookmark"></i> Server</label>
<input type="text" id="node-input-server">
</div> </div>
<div class="form-row"> <div class="form-row">
<label>&nbsp;</label> <label>&nbsp;</label>
@ -35,10 +82,6 @@
<input type="checkbox" id="node-input-join" placeholder="" style="display: inline-block; width: auto; vertical-align: top;"> <input type="checkbox" id="node-input-join" placeholder="" style="display: inline-block; width: auto; vertical-align: top;">
<label for="node-input-join" style="width: 70%;">Is a Chat Room ?</label> <label for="node-input-join" style="width: 70%;">Is a Chat Room ?</label>
</div> </div>
<div class="form-row">
<label for="node-input-nick"><i class="icon-user"></i> Nickname</label>
<input type="text" id="node-input-nick" placeholder="Joe">
</div>
<div class="form-row"> <div class="form-row">
<label for="node-input-name"><i class="icon-tag"></i> Name</label> <label for="node-input-name"><i class="icon-tag"></i> Name</label>
<input type="text" id="node-input-name" placeholder="Name"> <input type="text" id="node-input-name" placeholder="Name">
@ -46,41 +89,106 @@
<div class="form-tips">The <b>To</b> field is optional. If not set uses the <b>msg.topic</b> property of the message.</div> <div class="form-tips">The <b>To</b> field is optional. If not set uses the <b>msg.topic</b> property of the message.</div>
</script> </script>
<script type="text/x-red" data-help-name="xmpp"> <script type="text/x-red" data-help-name="xmpp out">
<p>Connects to an XMPP server to send and receive messages.</p> <p>Connects to an XMPP server to send messages.</p>
<p>Incoming messages will appear as <b>msg.payload</b> on the first output, while <b>msg.topic</b> will contain who it is from.</p> <p>The <b>To</b> field is optional. If not set the <b>msg.topic</b> property of the message is used.</p>
<p>The second output will user presence and status in <b>msg.payload</b>.</p>
<p>The <b>To</b> field is optional. If not set uses the <b>msg.topic</b> property of the message.</p>
<p>If you are joining a room then the <b>To</b> field must be filled in.</p> <p>If you are joining a room then the <b>To</b> field must be filled in.</p>
<p>Uses the simple-xmpp module - you may also need to pre-configure your xmpp settings as per below.</p> <p>You may also send a msg with <b>msg.presence</b> to set your presence to one of <i>chat, away, dnd</i> or <i>xa</i>.
<p>Either add to your settings.js file...</p> If you do so then the <b>msg.payload</b> will set your status message.</p>
<p><pre>xmpp : { jid : "yourid", password: "password" },</pre></p>
<p>Or create a file xmppkeys.js containing</p>
<p><pre>module.exports = { jid: "yourid", password: "password" }</pre></p>
<p>This <b>must</b> be located in the directory above node-red.</p>
</script> </script>
<script type="text/javascript"> <script type="text/javascript">
RED.nodes.registerType('xmpp',{ RED.nodes.registerType('xmpp out',{
category: 'advanced-function', category: 'social-output',
color:"Silver", color:"#F4F492",
defaults: { defaults: {
name: {value:""}, name: {value:""},
server: { value:"",required:true}, server: {type:"xmpp-server",required:true},
port: {value:5222,required:true},
to: {value:""}, to: {value:""},
join: {value:false}, join: {value:false},
sendObject: {value:false}, sendObject: {value:false}
nick: {value:""}
}, },
inputs:1, inputs:1,
outputs:2, outputs:0,
icon: "xmpp.png", icon: "xmpp.png",
align: "right",
label: function() { label: function() {
return this.name||this.server||"xmpp"; return this.name||"xmpp";
}, },
labelStyle: function() { labelStyle: function() {
return (this.name||!this.server)?"node_label_italic":""; return (this.name)?"node_label_italic":"";
}
});
</script>
<script type="text/x-red" data-template-name="xmpp-server">
<div class="form-row node-input-server">
<label for="node-config-input-server"><i class="icon-bookmark"></i> Server</label>
<input class="input-append-left" type="text" id="node-config-input-server" placeholder="localhost" style="width: 40%;" >
<label for="node-config-input-port" style="margin-left: 10px; width: 35px; "> Port</label>
<input type="text" id="node-config-input-port" placeholder="Port" style="width:45px">
</div>
<div class="form-row">
<label for="node-config-input-nickname"><i class="icon-user"></i> Nickname</label>
<input type="text" id="node-config-input-nickname" placeholder="Joe">
</div>
<div class="form-row">
<label for="node-config-input-user"><i class="icon-user"></i> Username</label>
<input type="text" id="node-config-input-user">
</div>
<div class="form-row">
<label for="node-config-input-pass"><i class="icon-lock"></i> Password</label>
<input type="password" id="node-config-input-pass">
</div>
<div class="form-tips" id="node-config-cred-tip"><b>Note:</b> Using credentials from global xmppkey.js file.</div>
</script>
<script type="text/javascript">
RED.nodes.registerType('xmpp-server',{
category: 'config',
defaults: {
server: {required:true},
port: {value:5222,required:true,validate:RED.validators.number()},
nickname: {}
},
label: function() {
return (this.nickname?this.nickname+"@":"")+this.server+":"+this.port;
},
oneditprepare: function() {
$.getJSON('xmpp-server/'+this.id,function(data) {
if (data.user) {
$('#node-config-input-user').val(data.user);
}
if (data.hasPassword) {
$('#node-config-input-pass').val('__PWRD__');
} else {
$('#node-config-input-pass').val('');
}
if (data.global) $('#node-config-cred-tip').show();
else $('#node-config-cred-tip').hide();
});
},
oneditsave: function() {
var credentials = {};
var newUser = $('#node-config-input-user').val();
var newPass = $('#node-config-input-pass').val();
credentials.user = newUser;
if (newPass != '__PWRD__') {
credentials.password = newPass;
}
$.ajax({
url: 'xmpp-server/'+this.id,
type: 'POST',
data: credentials,
success: function(result){}
});
},
ondelete: function() {
$.ajax({
url: 'xmpp-server/'+this.id,
type: 'DELETE',
success: function(result) {}
});
} }
}); });
</script> </script>

View File

@ -1,5 +1,5 @@
/** /**
* Copyright 2013 IBM Corp. * Copyright 2013,2014 IBM Corp.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -14,48 +14,92 @@
* limitations under the License. * limitations under the License.
**/ **/
var orig=console.warn; module.exports = function(RED) {
console.warn=(function() { // suppress warning from stringprep when not needed) "use strict";
var orig=console.warn; var XMPP = require('simple-xmpp');
return function() {
//orig.apply(console, arguments);
};
})();
var RED = require(process.env.NODE_RED_HOME+"/red/red"); try { var xmppkey = RED.settings.xmpp || require(process.env.NODE_RED_HOME+"/../xmppkeys.js"); }
var xmpp = require('simple-xmpp'); catch(err) { }
console.warn = orig;
try { function XMPPServerNode(n) {
var xmppkey = RED.settings.xmpp || require(process.env.NODE_RED_HOME+"/../xmppkeys.js");
} catch(err) {
throw new Error("Failed to load XMPP credentials");
}
function XmppNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.server = n.server; this.server = n.server;
this.port = n.port; this.port = n.port;
this.nickname = n.nickname;
var credentials = RED.nodes.getCredentials(n.id);
if (credentials) {
this.username = credentials.user;
this.password = credentials.password;
}
}
RED.nodes.registerType("xmpp-server",XMPPServerNode);
var querystring = require('querystring');
RED.httpAdmin.get('/xmpp-server/:id',function(req,res) {
var credentials = RED.nodes.getCredentials(req.params.id);
if (credentials) {
res.send(JSON.stringify({user:credentials.user,hasPassword:(credentials.password&&credentials.password!="")}));
} else if (xmppkey && xmppkey.jid && xmppkey.password) {
RED.nodes.addCredentials(req.params.id,{user:xmppkey.jid, password:xmppkey.password, global:true});
credentials = RED.nodes.getCredentials(req.params.id);
res.send(JSON.stringify({user:credentials.user,global:credentials.global,hasPassword:(credentials.password&&credentials.password!="")}));
} else {
res.send(JSON.stringify({}));
}
});
RED.httpAdmin.delete('/xmpp-server/:id',function(req,res) {
RED.nodes.deleteCredentials(req.params.id);
res.send(200);
});
RED.httpAdmin.post('/xmpp-server/:id',function(req,res) {
var body = "";
req.on('data', function(chunk) {
body+=chunk;
});
req.on('end', function(){
var newCreds = querystring.parse(body);
var credentials = RED.nodes.getCredentials(req.params.id)||{};
if (newCreds.user == null || newCreds.user == "") {
delete credentials.user;
} else {
credentials.user = newCreds.user;
}
if (newCreds.password == "") {
delete credentials.password;
} else {
credentials.password = newCreds.password||credentials.password;
}
RED.nodes.addCredentials(req.params.id,credentials);
res.send(200);
});
});
function XmppInNode(n) {
RED.nodes.createNode(this,n);
this.server = n.server;
this.serverConfig = RED.nodes.getNode(this.server);
this.host = this.serverConfig.server;
this.port = this.serverConfig.port;
this.nick = this.serverConfig.nickname || "Node-RED";
this.userid = this.serverConfig.username;
this.password = this.serverConfig.password;
this.join = n.join || false; this.join = n.join || false;
this.nick = n.nick || "Node-RED";
this.sendAll = n.sendObject; this.sendAll = n.sendObject;
this.to = n.to || ""; this.to = n.to || "";
var node = this; var node = this;
setTimeout(function() { var xmpp = new XMPP.SimpleXMPP();
xmpp.connect({
jid : xmppkey.jid,
password : xmppkey.password,
host : this.server,
port : this.port,
skipPresence : true,
reconnect : false
});
}, 5000);
xmpp.on('online', function() { xmpp.on('online', function() {
node.log('connected to '+node.server); node.log('connected to '+node.host+":"+node.port);
xmpp.setPresence('online', node.nick+' online'); node.status({fill:"green",shape:"dot",text:"connected"},true);
//xmpp.setPresence('online', node.nick+' online');
if (node.join) { if (node.join) {
xmpp.join(node.to+'/'+node.nick); xmpp.join(node.to+'/'+node.nick);
} }
@ -84,39 +128,126 @@ function XmppNode(n) {
}); });
xmpp.on('error', function(err) { xmpp.on('error', function(err) {
console.error(err); console.error("error",err);
}); });
xmpp.on('close', function(err) { xmpp.on('close', function(err) {
node.log('connection closed'); node.log('connection closed');
node.status({fill:"red",shape:"ring",text:"not connected"},true);
}); });
xmpp.on('subscribe', function(from) { xmpp.on('subscribe', function(from) {
xmpp.acceptSubscription(from); xmpp.acceptSubscription(from);
}); });
this.on("input", function(msg) { // Now actually make the connection
try {
xmpp.connect({
jid : node.userid,
password : node.password,
host : node.host,
port : node.port,
skipPresence : true,
reconnect : false
});
} catch(e) {
node.error("Bad xmpp configuration");
node.status({fill:"red",shape:"ring",text:"not connected"},true);
}
node.on("close", function(done) {
//xmpp.setPresence('offline');
if (xmpp.conn) { xmpp.conn.end(); }
xmpp = null;
done();
});
}
RED.nodes.registerType("xmpp in",XmppInNode);
function XmppOutNode(n) {
RED.nodes.createNode(this,n);
this.server = n.server;
this.serverConfig = RED.nodes.getNode(this.server);
this.host = this.serverConfig.server;
this.port = this.serverConfig.port;
this.nick = this.serverConfig.nickname || "Node-RED";
this.userid = this.serverConfig.username;
this.password = this.serverConfig.password;
this.join = n.join || false;
this.sendAll = n.sendObject;
this.to = n.to || "";
var node = this;
var xmpp = new XMPP.SimpleXMPP();
xmpp.on('online', function() {
node.log('connected to '+node.host+":"+node.port);
node.status({fill:"green",shape:"dot",text:"connected"},true);
xmpp.setPresence('online', node.nick+' online');
if (node.join) {
xmpp.join(node.to+'/'+node.nick);
}
});
xmpp.on('error', function(err) {
console.error("error",err);
});
xmpp.on('close', function(err) {
node.log('connection closed');
node.status({fill:"red",shape:"ring",text:"not connected"},true);
});
xmpp.on('subscribe', function(from) {
xmpp.acceptSubscription(from);
});
// Now actually make the connection
try {
xmpp.connect({
jid : node.userid,
password : node.password,
host : node.host,
port : node.port,
skipPresence : true,
reconnect : false
});
} catch(e) {
node.error("Bad xmpp configuration");
node.status({fill:"red",shape:"ring",text:"not connected"},true);
}
node.on("input", function(msg) {
if (msg.presence) {
if (['away', 'dnd', 'xa','chat'].indexOf(msg.presence) > -1 ) {
xmpp.setPresence(msg.presence, msg.payload);
}
else { node.warn("Can't set presence - invalid value"); }
}
else {
var to = msg.topic; var to = msg.topic;
if (node.to != "") { to = node.to; } if (node.to != "") { to = node.to; }
if (node.sendAll) { if (node.sendAll) {
xmpp.send(to, JSON.stringify(msg), node.join); xmpp.send(to, JSON.stringify(msg), node.join);
} }
else { else if (msg.payload) {
xmpp.send(to, msg.payload, node.join); if (typeof(msg.payload) === "object") {
xmpp.send(to, JSON.stringify(msg.payload), node.join);
} else {
xmpp.send(to, msg.payload.toString(), node.join);
}
}
} }
}); });
this.on("close", function() { node.on("close", function() {
xmpp.setPresence('offline'); xmpp.setPresence('offline');
try { if (xmpp.conn) { xmpp.conn.end(); }
xmpp.disconnect(); xmpp = null;
// TODO - DCJ NOTE... this is not good. It leaves the connection up over a restart - which will end up with bad things happening...
// (but requires the underlying xmpp lib to be fixed, which does have an open bug request on fixing the close method - and a work around.
// see - https://github.com/simple-xmpp/node-simple-xmpp/issues/12 for the fix
} catch(e) {
this.warn("Due to an underlying bug in the xmpp library this does not disconnect old sessions. This is bad... A restart would be better.");
}
}); });
} }
RED.nodes.registerType("xmpp out",XmppOutNode);
RED.nodes.registerType("xmpp",XmppNode); }