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

add Status to email, http nodes (update copyright on tcp)

This commit is contained in:
Dave C-J 2014-05-13 11:39:59 +01:00
parent 0e8f0735cc
commit 6f0e619611
4 changed files with 115 additions and 102 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.
@ -15,7 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
var util = require("util"); var util = require("util");
var http = require("follow-redirects").http; var http = require("follow-redirects").http;
var https = require("follow-redirects").https; var https = require("follow-redirects").https;
@ -24,11 +24,11 @@ module.exports = function(RED) {
var getBody = require('raw-body'); var getBody = require('raw-body');
var mustache = require("mustache"); var mustache = require("mustache");
var querystring = require("querystring"); var querystring = require("querystring");
var cors = require('cors'); var cors = require('cors');
var jsonParser = express.json(); var jsonParser = express.json();
var urlencParser = express.urlencoded(); var urlencParser = express.urlencoded();
function rawBodyParser(req, res, next) { function rawBodyParser(req, res, next) {
if (req._body) return next(); if (req._body) return next();
req.body = ""; req.body = "";
@ -43,22 +43,22 @@ module.exports = function(RED) {
next(); next();
}); });
} }
function HTTPIn(n) { function HTTPIn(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
if (RED.settings.httpNodeRoot !== false) { if (RED.settings.httpNodeRoot !== false) {
this.url = n.url; this.url = n.url;
this.method = n.method; this.method = n.method;
var node = this; var node = this;
this.errorHandler = function(err,req,res,next) { this.errorHandler = function(err,req,res,next) {
node.warn(err); node.warn(err);
res.send(500); res.send(500);
}; };
this.callback = function(req,res) { this.callback = function(req,res) {
if (node.method == "post") { if (node.method == "post") {
node.send({req:req,res:res,payload:req.body}); node.send({req:req,res:res,payload:req.body});
@ -68,14 +68,14 @@ module.exports = function(RED) {
node.send({req:req,res:res}); node.send({req:req,res:res});
} }
} }
var corsHandler = function(req,res,next) { next(); } var corsHandler = function(req,res,next) { next(); }
if (RED.settings.httpNodeCors) { if (RED.settings.httpNodeCors) {
corsHandler = cors(RED.settings.httpNodeCors); corsHandler = cors(RED.settings.httpNodeCors);
RED.httpNode.options(this.url,corsHandler); RED.httpNode.options(this.url,corsHandler);
} }
if (this.method == "get") { if (this.method == "get") {
RED.httpNode.get(this.url,corsHandler,this.callback,this.errorHandler); RED.httpNode.get(this.url,corsHandler,this.callback,this.errorHandler);
} else if (this.method == "post") { } else if (this.method == "post") {
@ -85,7 +85,7 @@ module.exports = function(RED) {
} else if (this.method == "delete") { } else if (this.method == "delete") {
RED.httpNode.delete(this.url,corsHandler,this.callback,errorHandler); RED.httpNode.delete(this.url,corsHandler,this.callback,errorHandler);
} }
this.on("close",function() { this.on("close",function() {
var routes = RED.httpNode.routes[this.method]; var routes = RED.httpNode.routes[this.method];
for (var i = 0; i<routes.length; i++) { for (var i = 0; i<routes.length; i++) {
@ -109,8 +109,8 @@ module.exports = function(RED) {
} }
} }
RED.nodes.registerType("http in",HTTPIn); RED.nodes.registerType("http in",HTTPIn);
function HTTPOut(n) { function HTTPOut(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
var node = this; var node = this;
@ -131,7 +131,7 @@ module.exports = function(RED) {
}); });
} }
RED.nodes.registerType("http response",HTTPOut); RED.nodes.registerType("http response",HTTPOut);
function HTTPRequest(n) { function HTTPRequest(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
var nodeUrl = n.url; var nodeUrl = n.url;
@ -140,74 +140,77 @@ module.exports = function(RED) {
var node = this; var node = this;
var credentials = RED.nodes.getCredentials(n.id); var credentials = RED.nodes.getCredentials(n.id);
this.on("input",function(msg) { this.on("input",function(msg) {
var url; node.status({fill:"blue",shape:"dot",text:"requesting"});
if (msg.url) { var url;
url = msg.url; if (msg.url) {
} else if (isTemplatedUrl) { url = msg.url;
url = mustache.render(nodeUrl,msg); } else if (isTemplatedUrl) {
url = mustache.render(nodeUrl,msg);
} else {
url = nodeUrl;
}
var method = (msg.method||nodeMethod).toUpperCase();
var opts = urllib.parse(url);
opts.method = method;
opts.headers = {};
if (msg.headers) {
for (var v in msg.headers) {
opts.headers[v.toLowerCase()] = msg.headers[v];
}
}
if (credentials) {
opts.auth = credentials.user+":"+(credentials.password||"");
}
var payload = null;
if (msg.payload && (method == "POST" || method == "PUT") ) {
if (typeof msg.payload === "string" || Buffer.isBuffer(msg.payload)) {
payload = msg.payload;
} else if (typeof msg.payload == "number") {
payload = msg.payload+"";
} else { } else {
url = nodeUrl; if (opts.headers['content-type'] == 'application/x-www-form-urlencoded') {
} payload = querystring.stringify(msg.payload);
var method = (msg.method||nodeMethod).toUpperCase();
var opts = urllib.parse(url);
opts.method = method;
opts.headers = {};
if (msg.headers) {
for (var v in msg.headers) {
opts.headers[v.toLowerCase()] = msg.headers[v];
}
}
if (credentials) {
opts.auth = credentials.user+":"+(credentials.password||"");
}
var payload = null;
if (msg.payload && (method == "POST" || method == "PUT") ) {
if (typeof msg.payload === "string" || Buffer.isBuffer(msg.payload)) {
payload = msg.payload;
} else if (typeof msg.payload == "number") {
payload = msg.payload+"";
} else { } else {
if (opts.headers['content-type'] == 'application/x-www-form-urlencoded') { payload = JSON.stringify(msg.payload);
payload = querystring.stringify(msg.payload); if (opts.headers['content-type'] == null) {
} else { opts.headers['content-type'] = "application/json";
payload = JSON.stringify(msg.payload);
if (opts.headers['content-type'] == null) {
opts.headers['content-type'] = "application/json";
}
} }
} }
if (opts.headers['content-length'] == null) {
opts.headers['content-length'] = Buffer.byteLength(payload);
}
} }
if (opts.headers['content-length'] == null) {
var req = ((/^https/.test(url))?https:http).request(opts,function(res) { opts.headers['content-length'] = Buffer.byteLength(payload);
res.setEncoding('utf8'); }
msg.statusCode = res.statusCode; }
msg.headers = res.headers;
msg.payload = ""; var req = ((/^https/.test(url))?https:http).request(opts,function(res) {
res.on('data',function(chunk) { res.setEncoding('utf8');
msg.payload += chunk; msg.statusCode = res.statusCode;
}); msg.headers = res.headers;
res.on('end',function() { msg.payload = "";
node.send(msg); res.on('data',function(chunk) {
}); msg.payload += chunk;
}); });
req.on('error',function(err) { res.on('end',function() {
msg.payload = err.toString();
msg.statusCode = err.code;
node.send(msg); node.send(msg);
node.status({});
}); });
if (payload) { });
req.write(payload); req.on('error',function(err) {
} msg.payload = err.toString();
req.end(); msg.statusCode = err.code;
node.send(msg);
node.status({fill:"red",shape:"ring",text:err.code});
});
if (payload) {
req.write(payload);
}
req.end();
}); });
} }
RED.nodes.registerType("http request",HTTPRequest); RED.nodes.registerType("http request",HTTPRequest);
RED.httpAdmin.get('/http-request/:id',function(req,res) { RED.httpAdmin.get('/http-request/:id',function(req,res) {
var credentials = RED.nodes.getCredentials(req.params.id); var credentials = RED.nodes.getCredentials(req.params.id);
if (credentials) { if (credentials) {
@ -216,12 +219,12 @@ module.exports = function(RED) {
res.send(JSON.stringify({})); res.send(JSON.stringify({}));
} }
}); });
RED.httpAdmin.delete('/http-request/:id',function(req,res) { RED.httpAdmin.delete('/http-request/:id',function(req,res) {
RED.nodes.deleteCredentials(req.params.id); RED.nodes.deleteCredentials(req.params.id);
res.send(200); res.send(200);
}); });
RED.httpAdmin.post('/http-request/:id',function(req,res) { RED.httpAdmin.post('/http-request/:id',function(req,res) {
var body = ""; var body = "";
req.on('data', function(chunk) { req.on('data', function(chunk) {

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.

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.

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.
@ -23,13 +23,12 @@ module.exports = function(RED) {
} catch (e) { } catch (e) {
util.log("[61-email.js] - imap npm not installed - no inbound email available"); util.log("[61-email.js] - imap npm not installed - no inbound email available");
} }
//console.log(nodemailer.Transport.transports.SMTP.wellKnownHosts); //console.log(nodemailer.Transport.transports.SMTP.wellKnownHosts);
// module.exports = { service: "Gmail", user: "blahblah@gmail.com", pass: "password", server: "imap.gmail.com", port: "993" }
try { var globalkeys = RED.settings.email || require(process.env.NODE_RED_HOME+"/../emailkeys.js"); } try { var globalkeys = RED.settings.email || require(process.env.NODE_RED_HOME+"/../emailkeys.js"); }
catch(err) { } catch(err) { }
function EmailNode(n) { function EmailNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.topic = n.topic; this.topic = n.topic;
@ -50,7 +49,7 @@ module.exports = function(RED) {
} }
if (flag) { RED.nodes.addCredentials(n.id,{userid:this.userid, password:this.password, global:true}); } if (flag) { RED.nodes.addCredentials(n.id,{userid:this.userid, password:this.password, global:true}); }
var node = this; var node = this;
var smtpTransport = nodemailer.createTransport("SMTP",{ var smtpTransport = nodemailer.createTransport("SMTP",{
//service: emailkey.service, //service: emailkey.service,
// { // {
@ -66,10 +65,10 @@ module.exports = function(RED) {
pass: node.password pass: node.password
} }
}); });
this.on("input", function(msg) { this.on("input", function(msg) {
//node.log("email :",this.id,this.topic," received",msg.payload);
if (msg != null) { if (msg != null) {
node.status({fill:"blue",shape:"dot",text:"sending"},true);
if (smtpTransport) { if (smtpTransport) {
smtpTransport.sendMail({ smtpTransport.sendMail({
from: node.userid, // sender address from: node.userid, // sender address
@ -79,8 +78,10 @@ module.exports = function(RED) {
}, function(error, response) { }, function(error, response) {
if (error) { if (error) {
node.error(error); node.error(error);
node.status({fill:"red",shape:"ring",text:"post error"},true);
} else { } else {
node.log("Message sent: " + response.message); node.log("Message sent: " + response.message);
node.status({},true);
} }
}); });
} }
@ -89,7 +90,7 @@ module.exports = function(RED) {
}); });
} }
RED.nodes.registerType("e-mail",EmailNode); RED.nodes.registerType("e-mail",EmailNode);
function EmailInNode(n) { function EmailInNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.name = n.name; this.name = n.name;
@ -112,7 +113,7 @@ module.exports = function(RED) {
var node = this; var node = this;
this.interval_id = null; this.interval_id = null;
var oldmail = {}; var oldmail = {};
var imap = new Imap({ var imap = new Imap({
user: node.userid, user: node.userid,
password: node.password, password: node.password,
@ -123,16 +124,17 @@ module.exports = function(RED) {
connTimeout: node.repeat, connTimeout: node.repeat,
authTimeout: node.repeat authTimeout: node.repeat
}); });
if (!isNaN(this.repeat) && this.repeat > 0) { if (!isNaN(this.repeat) && this.repeat > 0) {
node.log("repeat = "+this.repeat); node.log("repeat = "+this.repeat);
this.interval_id = setInterval( function() { this.interval_id = setInterval( function() {
node.emit("input",{}); node.emit("input",{});
}, this.repeat ); }, this.repeat );
} }
this.on("input", function(msg) { this.on("input", function(msg) {
imap.once('ready', function() { imap.once('ready', function() {
node.status({fill:"blue",shape:"dot",text:"fetching"},true);
var pay = {}; var pay = {};
imap.openBox('INBOX', true, function(err, box) { imap.openBox('INBOX', true, function(err, box) {
if (box.messages.total > 0) { if (box.messages.total > 0) {
@ -170,6 +172,7 @@ module.exports = function(RED) {
}); });
f.on('error', function(err) { f.on('error', function(err) {
node.warn('fetch error: ' + err); node.warn('fetch error: ' + err);
node.status({fill:"red",shape:"ring",text:"fetch error"},true);
}); });
f.on('end', function() { f.on('end', function() {
if (JSON.stringify(pay) !== oldmail) { if (JSON.stringify(pay) !== oldmail) {
@ -178,44 +181,51 @@ module.exports = function(RED) {
node.log('received new email: '+pay.topic); node.log('received new email: '+pay.topic);
} }
else { node.log('duplicate not sent: '+pay.topic); } else { node.log('duplicate not sent: '+pay.topic); }
//node.status({fill:"green",shape:"dot",text:"ok"},true);
node.status({},true);
imap.end(); imap.end();
}); });
} }
else { else {
node.log("you have achieved inbox zero"); node.log("you have achieved inbox zero");
//node.status({fill:"green",shape:"dot",text:"ok"},true);
node.status({},true);
imap.end(); imap.end();
} }
}); });
}); });
imap.on('error', function(err) { node.status({fill:"grey",shape:"dot",text:"connecting"},true);
node.log(err);
});
imap.connect(); imap.connect();
}); });
imap.on('error', function(err) {
node.log(err);
node.status({fill:"red",shape:"ring",text:"connect error"},true);
});
this.on("error", function(err) { this.on("error", function(err) {
node.log("error: ",err); node.log("error: ",err);
}); });
this.on("close", function() { this.on("close", function() {
if (this.interval_id != null) { if (this.interval_id != null) {
clearInterval(this.interval_id); clearInterval(this.interval_id);
} }
if (imap) { imap.destroy(); } if (imap) { imap.destroy(); }
}); });
node.emit("input",{}); node.emit("input",{});
} }
if (Imap != null) { if (Imap != null) {
RED.nodes.registerType("e-mail in",EmailInNode); RED.nodes.registerType("e-mail in",EmailInNode);
} }
var querystring = require('querystring'); var querystring = require('querystring');
RED.httpAdmin.get('/email/global',function(req,res) { RED.httpAdmin.get('/email/global',function(req,res) {
res.send(JSON.stringify({hasToken:!(globalkeys && globalkeys.userid && globalkeys.password)})); res.send(JSON.stringify({hasToken:!(globalkeys && globalkeys.userid && globalkeys.password)}));
}); });
RED.httpAdmin.get('/email/:id',function(req,res) { RED.httpAdmin.get('/email/:id',function(req,res) {
var credentials = RED.nodes.getCredentials(req.params.id); var credentials = RED.nodes.getCredentials(req.params.id);
if (credentials) { if (credentials) {
@ -230,12 +240,12 @@ module.exports = function(RED) {
res.send(JSON.stringify({})); res.send(JSON.stringify({}));
} }
}); });
RED.httpAdmin.delete('/email/:id',function(req,res) { RED.httpAdmin.delete('/email/:id',function(req,res) {
RED.nodes.deleteCredentials(req.params.id); RED.nodes.deleteCredentials(req.params.id);
res.send(200); res.send(200);
}); });
RED.httpAdmin.post('/email/:id',function(req,res) { RED.httpAdmin.post('/email/:id',function(req,res) {
var body = ""; var body = "";
req.on('data', function(chunk) { req.on('data', function(chunk) {