Initial commit: Nextcloud Node-RED Docker image and custom nodes
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
module.exports = function(RED) {
|
||||
var https = require('https');
|
||||
var http = require('http');
|
||||
var url = require('url');
|
||||
|
||||
function OcsApiNode(config) {
|
||||
RED.nodes.createNode(this, config);
|
||||
var node = this;
|
||||
this.configNode = RED.nodes.getNode(config.nextcloud);
|
||||
this.endpoint = config.endpoint || '/ocs/v2.php/cloud/user';
|
||||
this.method = config.method || 'GET';
|
||||
|
||||
if (!this.configNode) {
|
||||
node.error("No Nextcloud configuration node selected");
|
||||
return;
|
||||
}
|
||||
|
||||
node.on('input', function(msg) {
|
||||
var baseUrl = node.configNode.baseUrl;
|
||||
var username = node.configNode.credentials.username;
|
||||
var password = node.configNode.credentials.password;
|
||||
|
||||
// Allow msg to override endpoint
|
||||
var apiPath = msg.endpoint || node.endpoint;
|
||||
var apiMethod = msg.method || node.method;
|
||||
|
||||
// Build full URL
|
||||
var fullUrl = baseUrl.replace(/\/+$/, '') + '/' + apiPath.replace(/^\/+/, '');
|
||||
var parsedUrl = url.parse(fullUrl);
|
||||
|
||||
// Add OCS headers
|
||||
var headers = {
|
||||
'OCS-APIRequest': 'true',
|
||||
'Accept': 'application/json',
|
||||
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
|
||||
};
|
||||
|
||||
if (msg.headers && typeof msg.headers === 'object') {
|
||||
Object.keys(msg.headers).forEach(function(k) {
|
||||
headers[k] = msg.headers[k];
|
||||
});
|
||||
}
|
||||
|
||||
var opts = {
|
||||
hostname: parsedUrl.hostname,
|
||||
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
|
||||
path: parsedUrl.path,
|
||||
method: apiMethod,
|
||||
headers: headers,
|
||||
rejectUnauthorized: false // Allow self-signed certs
|
||||
};
|
||||
|
||||
var transport = parsedUrl.protocol === 'https:' ? https : http;
|
||||
|
||||
node.log(apiMethod + ' ' + fullUrl);
|
||||
|
||||
var req = transport.request(opts, function(res) {
|
||||
var body = '';
|
||||
res.on('data', function(chunk) { body += chunk; });
|
||||
res.on('end', function() {
|
||||
msg.statusCode = res.statusCode;
|
||||
try {
|
||||
msg.payload = JSON.parse(body);
|
||||
} catch(e) {
|
||||
msg.payload = body;
|
||||
}
|
||||
node.send(msg);
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', function(err) {
|
||||
msg.error = err.message;
|
||||
node.error(apiMethod + ' ' + fullUrl + ' — ' + err.message, msg);
|
||||
});
|
||||
|
||||
if (msg.body) {
|
||||
req.write(typeof msg.body === 'string' ? msg.body : JSON.stringify(msg.body));
|
||||
}
|
||||
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
RED.nodes.registerType("ocs-api", OcsApiNode);
|
||||
}
|
||||
Reference in New Issue
Block a user