Merge pull request #146 from Skylar-Tech/dev

Next release v1.1.0
This commit is contained in:
2026-10-16 11:23:00 -06:00
committed by GitHub
58 changed files with 1804 additions and 751 deletions
+9 -9
View File
@@ -1,17 +1,17 @@
{
"name": "node-red-contrib-matrix-chat",
"version": "1.0.0",
"version": "1.1.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "node-red-contrib-matrix-chat",
"version": "1.0.0",
"version": "1.1.0",
"license": "SEE LICENSE FILE",
"dependencies": {
"abort-controller": "^3.0.0",
"commonmark": "^0.31.2",
"fake-indexeddb": "^6.2.5",
"fake-indexeddb": "^6.2.6",
"fluent-ffmpeg": "^2.1.2",
"fs-extra": "^11.1.0",
"got": "^15.0.5",
@@ -8364,9 +8364,9 @@
}
},
"node_modules/fake-indexeddb": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.5.tgz",
"integrity": "sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==",
"version": "6.2.6",
"resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.6.tgz",
"integrity": "sha512-ihhmr0KoET51jT8R4YhbUYuLLvr1qqO6INISygtN16i8loR8kAxtAUr4+EKHTSMjL+lggaAn4OC7DRqzrNgnuQ==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
@@ -21831,9 +21831,9 @@
}
},
"fake-indexeddb": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.5.tgz",
"integrity": "sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w=="
"version": "6.2.6",
"resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.6.tgz",
"integrity": "sha512-ihhmr0KoET51jT8R4YhbUYuLLvr1qqO6INISygtN16i8loR8kAxtAUr4+EKHTSMjL+lggaAn4OC7DRqzrNgnuQ=="
},
"fast-glob": {
"version": "3.3.1",
+2 -2
View File
@@ -1,11 +1,11 @@
{
"name": "node-red-contrib-matrix-chat",
"version": "1.0.0",
"version": "1.1.0",
"description": "Matrix chat server client for Node-RED",
"dependencies": {
"abort-controller": "^3.0.0",
"commonmark": "^0.31.2",
"fake-indexeddb": "^6.2.5",
"fake-indexeddb": "^6.2.6",
"fluent-ffmpeg": "^2.1.2",
"fs-extra": "^11.1.0",
"got": "^15.0.5",
+7 -4
View File
@@ -27,21 +27,24 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
node.warn("No matrix server selected");
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -61,7 +64,7 @@ module.exports = function(RED) {
msg.topic = e.room_id;
node.send([msg, null]);
}).catch(function(e){
node.warn("Error creating room " + e);
node.error("Error creating room " + e, msg);
msg.error = e;
node.send([null, msg]);
});
+1 -1
View File
@@ -69,7 +69,7 @@
<dd>filename of the decoded file (if content.filename isn't defined on the message we fallback to content.body).</dd>
<dt>msg.thumbnail_payload <span class="property-type">buffer</span></dt>
<dd>If the file is an image then this property is set to the buffer of the thumbnail. If not an image this is left off.</dd>
<dd>If the media includes an encrypted thumbnail (images, videos, etc) this property is set to the decrypted thumbnail buffer. If there is no thumbnail this is left off.</dd>
</dl>
</li>
<li>Error
+13 -58
View File
@@ -13,21 +13,29 @@ module.exports = function(RED) {
if(!msg.type) {
node.error('msg.type is required.', msg);
msg.error = 'msg.type is required.';
node.send([null, msg]);
return;
}
if(!msg.content) {
node.error('msg.content is required.', msg);
msg.error = 'msg.content is required.';
node.send([null, msg]);
return;
}
if(!msg.content.file) {
node.error('msg.content.file is required.', msg);
msg.error = 'msg.content.file is required.';
node.send([null, msg]);
return;
}
if(!msg.url) {
node.error('msg.url is required.', msg);
msg.error = 'msg.url is required.';
node.send([null, msg]);
return;
}
@@ -37,17 +45,17 @@ module.exports = function(RED) {
let buffer = await downloadBufferWithFallback(got, msg.url, requestOptions);
msg.payload = Buffer.from(await decryptAttachment(buffer, msg.content.file));
// handle thumbnail decryption if necessary
// decrypt the thumbnail for any media type that ships an
// encrypted one (images, videos, etc), not just m.image
if(
msg.type.toLowerCase() === 'm.image'
&& msg.thumbnail_url
&& msg.content.info.thumbnail_file
msg.thumbnail_url
&& msg.content.info?.thumbnail_file
) {
let thumb_buffer = await downloadBufferWithFallback(got, msg.thumbnail_url, requestOptions);
msg.thumbnail_payload = Buffer.from(await decryptAttachment(thumb_buffer, msg.content.info.thumbnail_file));
}
} catch(error){
node.error(error);
node.error("Error decrypting file: " + error, msg);
msg.error = error;
node.send([null, msg]);
return;
@@ -115,59 +123,6 @@ module.exports = function(RED) {
}
// the following was taken & modified from https://github.com/matrix-org/browser-encrypt-attachment/blob/master/index.js
/**
* Encrypt an attachment.
* @param {ArrayBuffer} plaintextBuffer The attachment data buffer.
* @return {Promise} A promise that resolves with an object when the attachment is encrypted.
* The object has a "data" key with an ArrayBuffer of encrypted data and an "info" key
* with an object containing the info needed to decrypt the data.
*/
function encryptAttachment(plaintextBuffer) {
let cryptoKey; // The AES key object.
let exportedKey; // The AES key exported as JWK.
let ciphertextBuffer; // ArrayBuffer of encrypted data.
let sha256Buffer; // ArrayBuffer of digest.
let ivArray; // Uint8Array of AES IV
// Generate an IV where the first 8 bytes are random and the high 8 bytes
// are zero. We set the counter low bits to 0 since it makes it unlikely
// that the 64 bit counter will overflow.
ivArray = new Uint8Array(16);
crypto.getRandomValues(ivArray.subarray(0,8));
// Load the encryption key.
return crypto.subtle.generateKey(
{"name": "AES-CTR", length: 256}, true, ["encrypt", "decrypt"]
).then(function(generateKeyResult) {
cryptoKey = generateKeyResult;
// Export the Key as JWK.
return crypto.subtle.exportKey("jwk", cryptoKey);
}).then(function(exportKeyResult) {
exportedKey = exportKeyResult;
// Encrypt the input ArrayBuffer.
// Use half of the iv as the counter by setting the "length" to 64.
return crypto.subtle.encrypt(
{name: "AES-CTR", counter: ivArray, length: 64}, cryptoKey, plaintextBuffer
);
}).then(function(encryptResult) {
ciphertextBuffer = encryptResult;
// SHA-256 the encrypted data.
return crypto.subtle.digest("SHA-256", ciphertextBuffer);
}).then(function (digestResult) {
sha256Buffer = digestResult;
return {
data: ciphertextBuffer,
info: {
v: "v2",
key: exportedKey,
iv: encodeBase64(ivArray),
hashes: {
sha256: encodeBase64(new Uint8Array(sha256Buffer)),
},
},
};
});
}
/**
* Decrypt an attachment.
* @param {ArrayBuffer} ciphertextBuffer The encrypted attachment data buffer.
+19
View File
@@ -88,6 +88,12 @@ async function restoreCryptoStore(filePath) {
if (existing.has(dbSpec.name)) {
continue; // already live in memory - don't overwrite
}
if (!Array.isArray(dbSpec.stores) || !dbSpec.stores.length) {
// An empty database at the store's version would stop the Rust
// crypto stack from creating its schema - leave it out so it
// initializes fresh instead.
continue;
}
const openReq = indexedDB.open(dbSpec.name, dbSpec.version);
openReq.onupgradeneeded = () => {
@@ -152,6 +158,14 @@ async function snapshotCryptoStore(filePath, dbNamePrefix) {
const out = [];
for (const { name, version } of dbList) {
const db = await reqAsync(indexedDB.open(name, version));
if (!db.objectStoreNames.length) {
// Nothing worth persisting, and opening a database that was just
// deleted recreates it empty. Writing that shell to disk would make
// the Rust crypto stack fail on the next start
// ("No objectStore named core").
db.close();
continue;
}
const stores = [];
for (const storeName of Array.from(db.objectStoreNames)) {
const tx = db.transaction(storeName, 'readonly');
@@ -172,6 +186,11 @@ async function snapshotCryptoStore(filePath, dbNamePrefix) {
db.close();
out.push({ name, version, stores });
}
if (!out.length) {
// Nothing in memory (e.g. the store was not restored yet). Writing
// that would replace a good snapshot with an empty one.
return false;
}
const tmp = `${filePath}.tmp`;
fs.writeFileSync(tmp, v8.serialize(out));
+10 -5
View File
@@ -17,11 +17,11 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
@@ -34,11 +34,14 @@ module.exports = function(RED) {
}
if (!node.server || !node.server.matrixClient) {
node.warn("No matrix server selected");
node.error("No matrix server selected", msg);
msg.error = "No matrix server selected";
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -46,7 +49,9 @@ module.exports = function(RED) {
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
node.warn("Room must be specified in msg.topic or in configuration");
node.error("Room must be specified in msg.topic or in configuration", msg);
msg.error = "Room must be specified in msg.topic or in configuration";
node.send([null, msg]);
return;
}
@@ -65,7 +70,7 @@ module.exports = function(RED) {
node.send([msg, null]);
})
.catch(function(e){
node.warn("Error deleting event " + e);
node.error("Error deleting event " + e, msg);
msg.error = e;
msg.deleted = false
node.send([null, msg]);
+5 -3
View File
@@ -34,17 +34,19 @@ module.exports = function(RED) {
}
node.server.register(node);
node.server.on("disconnected", function() {
node.server.listen(node, "disconnected", function() {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", async function(msg) {
if (!node.server || !node.server.matrixClient) {
node.error("No matrix server selected", msg);
msg.error = "No matrix server selected";
node.error(msg.error, msg);
node.send([null, msg]);
return;
}
View File
+6 -6
View File
@@ -70,11 +70,11 @@
<h3>Inputs</h3>
<dl class="message-properties">
<dt>msg.payload.roomId <span class="property-type">string</span></dt>
<dd>The Room ID from which the event will be fetched.</dd>
<dt>msg.topic | dynamic <span class="property-type">string</span></dt>
<dd>The Room ID from which the event will be fetched. Read from <code>msg.topic</code> by default; configurable on the node.</dd>
<dt>msg.payload.eventId <span class="property-type">string</span></dt>
<dd>The Event ID of the message to fetch.</dd>
<dt>msg.eventId | dynamic <span class="property-type">string</span></dt>
<dd>The Event ID of the message to fetch. Read from <code>msg.eventId</code> by default; configurable on the node.</dd>
</dl>
<h3>Outputs</h3>
@@ -87,8 +87,8 @@
</li>
<li>Error
<dl class="message-properties">
<dt>msg.payload <span class="property-type">string</span></dt>
<dd>Error details.</dd>
<dt>msg.error <span class="property-type">string|object</span></dt>
<dd>Error details (also copied to <code>msg.payload</code> for older flows).</dd>
</dl>
</li>
</ol>
+13 -6
View File
@@ -19,22 +19,24 @@ module.exports = function(RED) {
}
node.server.register(node);
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on('input', async function(msg) {
if (! node.server || ! node.server.matrixClient) {
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if (!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -63,18 +65,23 @@ module.exports = function(RED) {
eventId = getToValue(msg, node.eventIdType, node.eventIdValue);
if(!roomId) {
node.error('Missing roomId', msg);
msg.error = 'Missing roomId';
node.error(msg.error, msg);
node.send([null, msg]);
return;
} else if(!eventId) {
node.error('Missing eventId', msg);
msg.error = 'Missing eventId';
node.error(msg.error, msg);
node.send([null, msg]);
return;
}
msg.payload = await node.server.matrixClient.fetchRoomEvent(roomId, eventId);
node.send([msg, null]);
} catch(e) {
node.error("Failed to get event " + msg.topic + ": " + e, msg);
msg.payload = e;
node.error("Failed to get event: " + e, msg);
msg.error = e;
msg.payload = e; // kept for flows written against older versions
node.send([null, msg]);
}
});
+13 -9
View File
@@ -43,13 +43,17 @@
<dd>Original message object with modifications based on config.</dd>
</dl>
<dl class="message-properties">
<dt>msg.error <span class="property-type">undefined|object</span></dt>
<dd>Returned if there was an error getting the user</dd>
<dt class="optional">dynamic
<span class="property-type">object|null</span>
</dt>
<dd> The user (<code>userId</code>, <code>displayName</code>, <code>avatarUrl</code>, <code>presence</code>, <code>presenceStatusMsg</code>, ...) written to the configured output property (<code>null</code> if the server has no profile details for them). A user the server does not know goes to the error output. It is a plain copy, so changing it does not affect the Matrix client. Presence fields are only included when the homeserver shares them (usually only for users in a room with the bot).</dd>
</dl>
</li>
<li>Error
<dl class="message-properties">
<dt>msg.error <span class="property-type">string</span></dt>
<dd>The reason the user could not be looked up.</dd>
</dl>
<dt class="optional">dynamic
<span class="property-type">string|object</span>
</dt>
<dd> You configure what to return on the node.</dd>
</li>
</ol>
</script>
@@ -90,15 +94,15 @@
},
oneditprepare: function() {
$("#node-input-user").typedInput({
type: this.roomType,
type: this.userType,
types:['msg','flow','global','str'],
})
.typedInput('value', this.userValue)
.typedInput('type', this.userType);
$("#node-input-property").typedInput({
type: this.roomType,
types:['msg','flow','global','str'],
type: this.propertyType,
types:['msg','flow','global'],
})
.typedInput('value', this.propertyValue)
.typedInput('type', this.propertyType);
+34 -7
View File
@@ -19,11 +19,11 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
@@ -58,7 +58,6 @@ module.exports = function(RED) {
var callback = err => {
if (err) {
node.error(err, msg);
getterErrors[rule.p] = err.message;
}
}
target.set(contextKey.key, value, contextKey.store, callback);
@@ -83,7 +82,15 @@ module.exports = function(RED) {
return;
}
let userId = getToValue(msg, node.userType, node.userValue);
let userId;
try {
userId = getToValue(msg, node.userType, node.userValue);
} catch(e) {
msg.error = "Failed getting userId: " + e.message;
node.error(msg.error, msg);
node.send([null, msg]);
return;
}
if(!userId) {
msg.error = "Missing userId";
node.error(msg.error, msg);
@@ -112,15 +119,23 @@ module.exports = function(RED) {
user2.avatarUrl = profileInfo.avatar_url;
}
let presence = await node.server.matrixClient.getPresence(userId);
// Presence is optional: homeservers refuse it (403) for users
// we share no room with, or have it disabled entirely.
let presence = null;
try {
presence = await node.server.matrixClient.getPresence(userId);
} catch(e) {
presence = null;
}
if(presence && Object.keys(presence).length > 0) {
user2.currentlyActive = presence.currently_active;
user2.lastActiveAgo = presence.last_active_ago;
user2.presenceStatusMsg = presence.presence_status_msg;
user2.presenceStatusMsg = presence.status_msg;
user2.presence = presence.presence;
}
if(Object.keys(user2).length > 0) {
user2.userId = userId;
setToValue(user2, node.propertyType, node.propertyValue);
node.send([msg, null]);
return;
@@ -133,7 +148,19 @@ module.exports = function(RED) {
}
}
setToValue(user, node.propertyType, node.propertyValue);
// A plain copy of the SDK's cached User (without its private
// underscore fields), so changes made by the flow cannot alter the
// SDK's cache or strip the User's event listeners.
let userCopy = null;
if(user) {
userCopy = {};
Object.keys(user).forEach(function(key) {
if(!/^_/.test(key)) {
userCopy[key] = user[key];
}
});
}
setToValue(userCopy, node.propertyType, node.propertyValue);
node.send([msg, null]);
});
+15 -3
View File
@@ -28,21 +28,24 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -50,7 +53,16 @@ module.exports = function(RED) {
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
msg.error = "room must be defined in either msg.topic or in node config";
node.error("room must be defined in either msg.topic or in node config", msg);
node.send([null, msg]);
return;
}
if(!msg.userId) {
node.error("msg.userId was not set.", msg);
msg.error = "msg.userId was not set.";
node.send([null, msg]);
return;
}
@@ -62,7 +74,7 @@ module.exports = function(RED) {
msg.payload = e;
node.send([msg, null]);
}).catch(function(e){
node.warn("Error inviting to room " + e);
node.error("Error inviting " + msg.userId + " to room " + msg.topic + ": " + e, msg);
msg.error = e;
node.send([null, msg]);
});
+2 -7
View File
@@ -45,13 +45,8 @@
</dt>
<dd> Extra options that can be passed when joining a room.</dd>
<dt class="optional">msg.joinOpts.syncRoom
<span class="property-type">bool</span>
</dt>
<dd> True to do a room initial sync on the resulting room. If false, the returned Room object will have no current state. Default: true.</dd>
<dt class="optional">msg.joinOpts.inviteSignUrl
<span class="property-type">bool</span>
<span class="property-type">string</span>
</dt>
<dd> If the caller has a keypair 3pid invite, the signing URL is passed in this parameter.</dd>
@@ -69,7 +64,7 @@
<dd>ID of the joined room.</dd>
<dt>msg.payload <span class="property-type">object</span></dt>
<dd>Room object.</dd>
<dd>Details of the joined room: <code>roomId</code>, <code>name</code>, <code>canonicalAlias</code> and <code>membership</code> (always <code>join</code>). <code>name</code> and <code>canonicalAlias</code> are <code>null</code> if the bot was not in the room yet: the room's details only arrive with the next sync.</dd>
</dl>
</li>
<li>Error
+23 -5
View File
@@ -15,35 +15,53 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
}
if(!msg.topic) {
msg.error = "Room must be specified in msg.topic";
node.error("Room must be specified in msg.topic", msg);
node.send([null, msg]);
return;
}
node.server.matrixClient.joinRoom(msg.topic, msg.joinOpts || {})
.then(function(e) {
msg.payload = e;
msg.topic = e.roomId;
.then(function(room) {
// Plain data only: the SDK Room object references the whole
// client, so Node-RED cloning the msg (an output wired to
// more than one node) failed with "Maximum call stack size
// exceeded".
// After a fresh join the SDK returns a room without state
// (its name is the room ID and membership "leave") until
// the next sync, so only report the details it really has.
let synced = room.getMyMembership() === "join";
msg.payload = {
roomId: room.roomId,
name: synced ? (room.name || null) : null,
canonicalAlias: synced ? room.getCanonicalAlias() : null,
membership: "join",
};
msg.topic = room.roomId;
node.log("Successfully joined room " + msg.topic);
node.send([msg, null]);
})
+2 -2
View File
@@ -48,8 +48,8 @@
<ol class="node-ports">
<li>Success
<dl class="message-properties">
<dt>msg.payload <span class="property-type">object</span></dt>
<dd>Returns the same message that was received</dd>
<dt>msg <span class="property-type">object</span></dt>
<dd>the input message, unchanged.</dd>
</dl>
</li>
<li>Error
+22 -12
View File
@@ -16,41 +16,51 @@ module.exports = function(RED) {
}
node.server.register(node);
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on('input', function(msg) {
if (! node.server || ! node.server.matrixClient) {
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!msg.topic) {
msg.error = 'No room provided in msg.topic';
node.error('No room provided in msg.topic', msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
}
try {
node.log("Leaving room " + msg.topic);
node.server.matrixClient.leave(msg.topic);
node.server.matrixClient.store.removeRoom(msg.topic);
node.send([msg, null]);
} catch(e) {
node.error("Failed to leave room " + msg.topic + ": " + e, msg);
msg.payload = e;
node.send([null, msg]);
}
// leave() returns a promise: it used to be ignored, so a failed
// leave (e.g. not a member) still reported success and the
// rejection went unhandled.
node.log("Leaving room " + msg.topic);
node.server.matrixClient.leave(msg.topic)
.then(function() {
node.server.matrixClient.store.removeRoom(msg.topic);
node.send([msg, null]);
})
.catch(function(e) {
node.error("Failed to leave room " + msg.topic + ": " + e, msg);
msg.error = e;
msg.payload = e;
node.send([null, msg]);
});
});
node.on("close", function() {
+2 -2
View File
@@ -3,7 +3,7 @@
category: 'matrix',
color: '#00b7ca',
icon: "matrix.png",
outputLabels: ["message"],
outputLabels: ["success", "error"],
inputs: 1,
outputs: 2,
defaults: {
@@ -27,7 +27,7 @@
.typedInput('type', this.roomType);
$("#node-input-eventId").typedInput({
types:['msg','flow','global','bool'],
types:['msg','flow','global','str'],
})
.typedInput('value', this.eventIdValue)
.typedInput('type', this.eventIdType);
+25 -6
View File
@@ -1,4 +1,4 @@
const crypto = require('crypto');
const sdkPromise = import("matrix-js-sdk");
module.exports = function(RED) {
function MatrixMarkRead(n) {
@@ -19,17 +19,26 @@ module.exports = function(RED) {
}
node.server.register(node);
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", async function (msg) {
if (!node.server || !node.server.matrixClient) {
node.error("No matrix server selected", msg);
msg.error = "No matrix server selected";
node.send([null, msg]);
return;
}
if (!node.server.isConnected()) {
node.error("Matrix server connection is currently closed", msg);
msg.error = "Matrix server connection is currently closed";
node.send([null, msg]);
return;
}
@@ -60,15 +69,25 @@ module.exports = function(RED) {
throw new Error(`Room ${roomId} not found.`);
}
const event = room.findEventById(eventId);
// findEventById only searches the loaded timeline; fetch older
// (or not yet synced) events from the server instead of
// failing with "not found".
let event = room.findEventById(eventId);
if (!event) {
throw new Error(`Event ${eventId} not found in room ${roomId}.`);
let raw;
try {
raw = await node.server.matrixClient.fetchRoomEvent(roomId, eventId);
} catch (e) {
throw new Error(`Event ${eventId} not found in room ${roomId}: ${e}`);
}
const { MatrixEvent } = await sdkPromise;
event = new MatrixEvent(raw);
}
await node.server.matrixClient.sendReceipt(event, "m.read");
node.send([msg, null]);
} catch (e) {
msg.error = `Room pagination error: ${e}`;
msg.error = `Mark read error: ${e}`;
node.error(msg.error, msg);
node.send([null, msg]);
}
+1 -1
View File
@@ -80,7 +80,7 @@
<div class="form-row">
<label for="node-input-paginateKey"><i class="fa fa-key"></i> Pagination Key</label>
<input type="text" id="node-input-paginateKey">
<div class="form-tips" style="margin-top: 10px;">A unique key to identify the current pagination session. If not provided, a new key will be generated for each session.</div>
<div class="form-tips" style="margin-top: 10px;">A unique key to identify the current pagination session. If not provided, a new key will be generated for each session. Up to 50 sessions are kept per node; when more are started, the least recently used session is dropped and its key starts over.</div>
</div>
<div class="form-row">
+39 -7
View File
@@ -17,6 +17,18 @@ module.exports = function(RED) {
this.pageSizeType = n.pageSizeType;
this.pageSizeValue = n.pageSizeValue;
this.timelineWindows = new Map();
// Each pagination key keeps a TimelineWindow, and the SDK attaches a
// listener for it to the room that it never removes. Keep at most
// this many (least recently used dropped first) and detach the
// listener of every window that is dropped.
const MAX_TIMELINE_WINDOWS = 50;
function dropTimelineWindow(pageKey) {
let entry = node.timelineWindows.get(pageKey);
if (entry && entry.listener) {
entry.room.removeListener(entry.event, entry.listener);
}
node.timelineWindows.delete(pageKey);
}
node.status({ fill: "red", shape: "ring", text: "disconnected" });
@@ -26,17 +38,19 @@ module.exports = function(RED) {
}
node.server.register(node);
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", async function (msg) {
if (!node.server || !node.server.matrixClient) {
node.error("No matrix server selected", msg);
msg.error = "No matrix server selected";
node.error(msg.error, msg);
node.send([null, msg]);
return;
}
@@ -102,21 +116,36 @@ module.exports = function(RED) {
pageKey = crypto.randomUUID();
setToValue(pageKey, node.paginateKeyType, node.paginateKeyValue);
}
let timelineWindow = node.timelineWindows.get(pageKey),
let entry = node.timelineWindows.get(pageKey),
timelineWindow = entry && entry.timelineWindow,
moreMessages = true;
if (!timelineWindow) {
let timelineSet = room.getUnfilteredTimelineSet();
// the SDK keeps no reference to the listener it adds, so
// find it by comparing the room's listeners
let before = new Set(room.listeners(sdk.RoomEvent.Timeline));
// MatrixClient's option initialSyncLimit gets set to the filter we are using,
// so override that value with our pageSize.
timelineWindow = new TimelineWindow(node.server.matrixClient, timelineSet);
let listener = room.listeners(sdk.RoomEvent.Timeline).find(function(l) { return !before.has(l); });
node.timelineWindows.set(pageKey, { timelineWindow, room, event: sdk.RoomEvent.Timeline, listener });
await timelineWindow.load(msg.eventId || null, pageSize);
node.timelineWindows.set(pageKey, timelineWindow);
} else {
// refresh the key's position so the cap below drops the least recently used
node.timelineWindows.delete(pageKey);
node.timelineWindows.set(pageKey, entry);
let previousCount = timelineWindow.getEvents().length;
moreMessages = await timelineWindow.paginate(paginateBackwards ? 'b' : 'f', pageSize); // 'b' for backwards, 'f' for forwards
if (moreMessages) {
await timelineWindow.unpaginate(pageSize, !paginateBackwards);
if (moreMessages && previousCount > 0) {
// Drop the previous page so only the new one is returned. Never
// more than the window holds: the SDK throws if asked to remove
// more events than it has (e.g. a short first page).
timelineWindow.unpaginate(Math.min(previousCount, timelineWindow.getEvents().length), !paginateBackwards);
}
}
while (node.timelineWindows.size > MAX_TIMELINE_WINDOWS) {
dropTimelineWindow(node.timelineWindows.keys().next().value);
}
// To avoid errors converting massive MatrixEvent objects to JSON, we omit them.
msg.payload = false;
@@ -149,6 +178,9 @@ module.exports = function(RED) {
});
node.on("close", function() {
for (let pageKey of Array.from(node.timelineWindows.keys())) {
dropTimelineWindow(pageKey);
}
node.server.deregister(node);
});
}
+12 -2
View File
@@ -17,21 +17,24 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (!node.server || !node.server.matrixClient) {
node.error("No matrix server selected", msg);
msg.error = "No matrix server selected";
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -40,18 +43,24 @@ module.exports = function(RED) {
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
node.error("Room must be specified in msg.topic or in configuration", msg);
msg.error = "Room must be specified in msg.topic or in configuration";
node.send([null, msg]);
return;
}
let payload = n.reaction || msg.payload;
if(!payload) {
node.error('msg.payload must be defined or the reaction configured on the node.', msg);
msg.error = 'msg.payload must be defined or the reaction configured on the node.';
node.send([null, msg]);
return;
}
let eventId = msg.referenceEventId || msg.eventId;
if(!eventId) {
node.error('Either msg.referenceEventId or msg.eventId must be defined to react to a message.', msg);
msg.error = 'Either msg.referenceEventId or msg.eventId must be defined to react to a message.';
node.send([null, msg]);
return;
}
@@ -73,6 +82,7 @@ module.exports = function(RED) {
node.send([msg, null]);
})
.catch(function(e){
node.error("Error sending reaction: " + e, msg);
msg.error = e;
node.send([null, msg]);
});
+2 -2
View File
@@ -300,12 +300,12 @@
<li><code>msg.type</code> == '<strong>m.audio</strong>'
<dl class="message-properties">
<dt>msg.filename <span class="property-type">string</span></dt>
<dd>the image's parsed filename</dd>
<dd>the audio file's name (from the event, falling back to its body)</dd>
</dl>
<dl class="message-properties">
<dt>msg.mimetype <span class="property-type">string</span></dt>
<dd>audio file mimetype (ex: audio/ogg)</dd>
<dd>audio file mimetype (ex: audio/ogg), if the sender included one</dd>
</dl>
<dl class="message-properties">
+70 -34
View File
@@ -41,20 +41,44 @@ module.exports = function(RED) {
}
node.server.register(node);
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.server.on("Room.timeline", async function(event, room, toStartOfTimeline, removed, data, msg) {
node.server.listen(node, "Room.timeline", async function(event, room, toStartOfTimeline, removed, data, sharedMsg) {
// This runs inside the SDK's event emission; an exception thrown
// here would become an unhandled rejection and can stop Node-RED.
try {
handleTimelineEvent(event, room, sharedMsg);
} catch(e) {
// a small msg for Catch nodes, so a Catch flow cannot modify the shared msg
node.error("Failed to process timeline event " + (event && event.getId ? event.getId() : "") + ": " + e, {
topic: sharedMsg && sharedMsg.topic, eventId: sharedMsg && sharedMsg.eventId,
userId: sharedMsg && sharedMsg.userId, type: sharedMsg && sharedMsg.type,
});
}
});
function handleTimelineEvent(event, room, sharedMsg) {
// if node has a room ID set we only listen on that room
if (node.roomIds.length && !node.roomIds.includes(room.roomId)) {
return;
}
// Every receive node gets the same msg from the config node, so
// work on a private copy: otherwise one flow changing its msg (or
// this node setting msg.url/payload) leaks into every other
// receive node's flow, and into the SDK's own event content
// (#144). The live MatrixEvent stays shared; deep-cloning it would
// copy the client it references.
const { event: liveEvent, ...plain } = sharedMsg;
const msg = RED.util.cloneMessage(plain);
msg.event = liveEvent;
if (!node.acceptOwnEvents && (!event.getSender() || event.getSender().toLowerCase() === node.server.matrixClient.getUserId().toLowerCase())) {
node.log(`Ignoring${msg.encrypted ? ' encrypted' : ''} timeline event [${msg.type}]: (${room.name}) ${event.getId()} for reason: own event`);
return;
@@ -71,8 +95,12 @@ module.exports = function(RED) {
};
const setUrls = (urlKey, encryptedKey) => {
const url = msg.encrypted ? msg.content[encryptedKey]?.url : msg.content[urlKey];
if (url) {
// Detect encrypted vs plain media by shape, not by whether the
// event is encrypted: an encrypted event can carry plain media
// (stickers always do, some clients and bridges do for files),
// where content.url is the mxc string.
const url = msg.content[encryptedKey]?.url || msg.content[urlKey];
if (typeof url === 'string' && url) {
const authenticatedUrl = node.server.matrixClient.mxcUrlToHttp(
url,
undefined,
@@ -88,23 +116,29 @@ module.exports = function(RED) {
}
};
const setThumbnailUrls = (infoKey) => {
const thumbnailFile = msg.content.info?.[infoKey];
const thumbnailUrl = thumbnailFile?.url;
if (thumbnailUrl) {
const authenticatedThumbnailUrl = node.server.matrixClient.mxcUrlToHttp(
thumbnailUrl,
undefined,
undefined,
undefined,
false,
true,
true,
);
msg.thumbnail_url = authenticatedThumbnailUrl || node.server.matrixClient.mxcUrlToHttp(thumbnailUrl);
msg.thumbnail_mxc_url = thumbnailUrl;
setAuthHeaders();
}
const setThumbnailUrls = () => {
const info = msg.content.info;
if (!info) return;
// A thumbnail is either encrypted - info.thumbnail_file, an
// EncryptedFile object whose .url holds the mxc - or unencrypted
// - info.thumbnail_url, a plain mxc string. Detect by shape so
// both image/video and encrypted/unencrypted events resolve a
// thumbnail (the old code only ever read an object .url, so
// unencrypted thumbnails were silently dropped).
const thumbnailUrl = info.thumbnail_file?.url || info.thumbnail_url;
if (typeof thumbnailUrl !== 'string' || !thumbnailUrl) return;
const authenticatedThumbnailUrl = node.server.matrixClient.mxcUrlToHttp(
thumbnailUrl,
undefined,
undefined,
undefined,
false,
true,
true,
);
msg.thumbnail_url = authenticatedThumbnailUrl || node.server.matrixClient.mxcUrlToHttp(thumbnailUrl);
msg.thumbnail_mxc_url = thumbnailUrl;
setAuthHeaders();
};
switch (msg.type) {
@@ -122,7 +156,7 @@ module.exports = function(RED) {
case 'm.sticker':
if (!node.acceptStickers) return;
setThumbnailUrls('thumbnail_url');
setThumbnailUrls();
setUrls('url', 'url');
break;
@@ -135,10 +169,8 @@ module.exports = function(RED) {
case 'm.audio':
if (!node.acceptAudio) return;
setUrls('url', 'file');
if ('org.matrix.msc1767.file' in msg.content) {
msg.filename = msg.content['org.matrix.msc1767.file'].name;
msg.mimetype = msg.content['org.matrix.msc1767.file'].mimetype;
}
msg.filename = msg.content['org.matrix.msc1767.file']?.name || msg.content.filename || msg.content.body;
msg.mimetype = msg.content['org.matrix.msc1767.file']?.mimetype || msg.content.info?.mimetype;
if ('org.matrix.msc1767.audio' in msg.content) {
msg.duration = msg.content['org.matrix.msc1767.audio'].duration;
msg.waveform = msg.content['org.matrix.msc1767.audio'].waveform;
@@ -149,14 +181,14 @@ module.exports = function(RED) {
if (!node.acceptImages) return;
msg.filename = msg.content.filename || msg.content.body;
setUrls('url', 'file');
setThumbnailUrls('thumbnail_file');
setThumbnailUrls();
break;
case 'm.video':
if (!node.acceptVideos) return;
msg.filename = msg.content.filename || msg.content.body;
setUrls('url', 'file');
setThumbnailUrls('thumbnail_file');
setThumbnailUrls();
break;
case 'm.location': {
@@ -185,19 +217,23 @@ module.exports = function(RED) {
break;
}
case 'm.reaction':
case 'm.reaction': {
if (!node.acceptReactions) return;
msg.info = msg.content["m.relates_to"].info;
msg.referenceEventId = msg.content["m.relates_to"].event_id;
msg.payload = msg.content["m.relates_to"].key;
// a redacted or malformed reaction has no m.relates_to
const relation = msg.content["m.relates_to"];
if (!relation) return;
msg.info = relation.info;
msg.referenceEventId = relation.event_id;
msg.payload = relation.key;
break;
}
default:
return;
}
node.send(msg);
});
}
node.on("close", function() {
node.server.deregister(node);
+3 -3
View File
@@ -35,7 +35,7 @@
</div>
<div class="form-row">
<label for="node-input-reason"><i class="fa fa-comment"></i> Reason</label>
<input type="text" id="node-input-reason" placeholder="msg.topic">
<input type="text" id="node-input-reason" placeholder="msg.reason">
</div>
<script type="text/javascript">
$(function(){
@@ -76,8 +76,8 @@
<ol class="node-ports">
<li>Success
<dl class="message-properties">
<dt>msg.eventId <span class="property-type">string</span></dt>
<dd>the eventId from the ban event.</dd>
<dt>msg <span class="property-type">object</span></dt>
<dd>the input message, unchanged (the server does not return an event id for a ban).</dd>
</dl>
</li>
<li>Error
+11 -4
View File
@@ -17,21 +17,24 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -39,19 +42,23 @@ module.exports = function(RED) {
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
msg.error = "Room must be specified in msg.topic or in configuration";
node.error("Room must be specified in msg.topic or in configuration", msg);
node.send([null, msg]);
return;
}
if(!msg.userId) {
msg.error = "msg.userId was not set.";
node.error("msg.userId was not set.", msg);
node.send([null, msg]);
return;
}
node.server.matrixClient.ban(msg.topic, msg.userId, n.reason || msg.reason || undefined)
.then(function(e) {
.then(function() {
// the endpoint returns {} (no event id), so msg is passed on unchanged
node.log("Successfully banned " + msg.userId + " from " + msg.topic);
msg.eventId = e.event_id;
node.send([msg, null]);
})
.catch(function(e){
+5 -9
View File
@@ -3,7 +3,7 @@
category: 'matrix',
color: '#00b7ca',
icon: "matrix.png",
outputLabels: ["success", "error"],
outputLabels: ["invite"],
inputs: 0,
outputs: 1,
defaults: {
@@ -33,12 +33,14 @@
<script type="text/html" data-help-name="matrix-room-invite">
<h3>Details</h3>
<p>
This node receives room invites.
This node receives room invites. If "Auto join invited rooms" is off on the
server configuration, invites that are still pending are reported again each
time Node-RED starts or the flows are fully deployed.
</p>
<h3>Outputs</h3>
<ol class="node-ports">
<li>Success
<li>Invite
<dl class="message-properties">
<dt>msg.type <span class="property-type">string</span></dt>
<dd>Always <code>m.room.member</code></dd>
@@ -69,12 +71,6 @@
<dd>The ID of the event for this invite.</dd>
</dl>
</li>
<li>Error
<dl class="message-properties">
<dt>msg.error <span class="property-type">string</span></dt>
<dd>the error that occurred.</dd>
</dl>
</li>
</ol>
</script>
+8 -3
View File
@@ -16,15 +16,20 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.server.on("Room.invite", async function(msg) {
node.server.listen(node, "Room.invite", function(sharedMsg) {
// every Room Invite node gets the same msg; send a private copy
// (the live MatrixEvent stays shared, like in matrix-receive)
const { event, ...plain } = sharedMsg;
const msg = RED.util.cloneMessage(plain);
msg.event = event;
node.send(msg);
});
+3 -3
View File
@@ -35,7 +35,7 @@
</div>
<div class="form-row">
<label for="node-input-reason"><i class="fa fa-comment"></i> Reason</label>
<input type="text" id="node-input-reason" placeholder="msg.topic">
<input type="text" id="node-input-reason" placeholder="msg.reason">
</div>
<script type="text/javascript">
$(function(){
@@ -76,8 +76,8 @@
<ol class="node-ports">
<li>Success
<dl class="message-properties">
<dt>msg.eventId <span class="property-type">string</span></dt>
<dd>the eventId from the kick event.</dd>
<dt>msg <span class="property-type">object</span></dt>
<dd>the input message, unchanged (the server does not return an event id for a kick).</dd>
</dl>
</li>
<li>Error
+11 -4
View File
@@ -17,21 +17,24 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -39,19 +42,23 @@ module.exports = function(RED) {
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
msg.error = "Room must be specified in msg.topic or in configuration";
node.error("Room must be specified in msg.topic or in configuration", msg);
node.send([null, msg]);
return;
}
if(!msg.userId) {
msg.error = "msg.userId was not set.";
node.error("msg.userId was not set.", msg);
node.send([null, msg]);
return;
}
node.server.matrixClient.kick(msg.topic, msg.userId, n.reason || msg.reason || undefined)
.then(function(e) {
.then(function() {
// the endpoint returns {} (no event id), so msg is passed on unchanged
node.log("Successfully kicked " + msg.userId + " from " + msg.topic);
msg.eventId = e.event_id;
node.send([msg, null]);
})
.catch(function(e){
+4 -4
View File
@@ -35,12 +35,12 @@
<dt class="optional">dynamic
<span class="property-type">string|object</span>
</dt>
<dd> You configure what room state events in the node configuration. <code style="white-space: normal;">m.room.name</code>, <code style="white-space: normal;">m.room.avatar</code>, and <code style="white-space: normal;">m.room.guest_access</code> allow you to pass a string to set their value but all other room state events will require the full content object (find this by referencing the <a href="https://spec.matrix.org/latest/client-server-api" target="_blank">Matrix Client-Server docs</a>)</dd>
<dd> You configure what room state events in the node configuration. <code style="white-space: normal;">m.room.name</code>, <code style="white-space: normal;">m.room.topic</code>, <code style="white-space: normal;">m.room.avatar</code>, and <code style="white-space: normal;">m.room.guest_access</code> allow you to pass a string to set their value but all other room state events will require the full content object (find this by referencing the <a href="https://spec.matrix.org/latest/client-server-api" target="_blank">Matrix Client-Server docs</a>)</dd>
<dt class="optional">msg.state_key
<span class="property-type">string</span>
</dt>
<dd> Required for some events such as <code style="white-space: normal;">m.space.parent</code> and <code style="white-space: normal;">m.room.child</code> to set the referenced child/parent room</dd>
<dd> The state key of the space event to set or get. Required for <code style="white-space: normal;">m.space.child</code> (sent in the space, state key = the child room ID) and <code style="white-space: normal;">m.space.parent</code> (sent in the child room, state key = the parent space ID). Other event types are read with an empty state key; when setting a custom event type it is used as that event's state key (defaults to empty).</dd>
</dl>
<h3>Outputs</h3>
@@ -56,12 +56,12 @@
</dl>
<dl class="message-properties">
<dt>msg.getter_errors <span class="property-type">undefined|object</span></dt>
<dd>Returned if getting a room state event failed. The key of the object is the room state event type and the value is the error that occurred. Note that you will get an error if you try getting a room state event that doesn't exist (such as fetching avatar on a room that doesn't have one).</dd>
<dd>Returned if getting a room state event failed. The key of the object is the room state event type and the value is the error message. Note that you will get an error if you try getting a room state event that doesn't exist (such as fetching avatar on a room that doesn't have one).</dd>
</dl>
<dt class="optional">dynamic
<span class="property-type">string|object</span>
</dt>
<dd> You configure what room state events to output in the node configuration. <code style="white-space: normal;">m.room.name</code>, <code style="white-space: normal;">m.room.avatar</code>, and <code style="white-space: normal;">m.room.guest_access</code> will come back as strings otherwise you will get the full content object of the event (find this by referencing the <a href="https://spec.matrix.org/latest/client-server-api" target="_blank">Matrix Client-Server docs</a>). Additionally there is a setting when configuring a getter called "Fetch from local storage" that if enabled will search the local storage for the room and try to fetch the state event that way and fallback to hitting the server if that isn't possible.</dd>
<dd> You configure what room state events to output in the node configuration. <code style="white-space: normal;">m.room.name</code>, <code style="white-space: normal;">m.room.topic</code>, <code style="white-space: normal;">m.room.avatar</code>, and <code style="white-space: normal;">m.room.guest_access</code> will come back as strings otherwise you will get the full content object of the event (find this by referencing the <a href="https://spec.matrix.org/latest/client-server-api" target="_blank">Matrix Client-Server docs</a>). Additionally there is a setting when configuring a getter called "Fetch from local storage" that if enabled will search the local storage for the room and try to fetch the state event that way and fallback to hitting the server if that isn't possible; both return the same value.</dd>
</li>
</ol>
</script>
+76 -39
View File
@@ -6,7 +6,9 @@ module.exports = function(RED) {
this.name = n.name;
this.server = RED.nodes.getNode(n.server);
this.roomId = n.roomId;
this.roomId = n.roomId; // legacy setting, superseded by the Room typed input
this.roomType = n.roomType;
this.roomValue = n.roomValue;
this.rules = n.rules;
if (!node.server) {
@@ -17,14 +19,26 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
// Room from the editor's Room typed input (defaults to msg.topic).
// Older configs only have the legacy roomId setting.
function getRoomId(msg) {
if (node.roomType === 'str') {
return node.roomValue || msg.topic;
}
if (node.roomType) {
return RED.util.evaluateNodeProperty(node.roomValue, node.roomType, node, msg);
}
return node.roomId || msg.topic;
}
node.on("input", async function (msg) {
if (! node.server || ! node.server.matrixClient) {
msg.error = "No matrix server selected";
@@ -40,7 +54,11 @@ module.exports = function(RED) {
return;
}
msg.topic = node.roomId || msg.topic;
try {
msg.topic = getRoomId(msg);
} catch(e) {
msg.topic = null;
}
if(!msg.topic) {
msg.error = "Room must be specified in msg.topic or in configuration";
node.error(msg.error, msg);
@@ -53,10 +71,11 @@ module.exports = function(RED) {
if(!Array.isArray(node.rules) || !node.rules.length) {
node.warn("No rules configured, skipping", msg);
return msg;
node.send([msg, null]);
return;
}
function getToValue(msg, rule) {
async function getToValue(msg, rule) {
var value = rule.to;
if (rule.tot === 'json') {
try {
@@ -82,12 +101,21 @@ module.exports = function(RED) {
} else if (rule.tot === 'date') {
value = Date.now();
} else if (rule.tot === 'jsonata') {
let expr;
try {
value = RED.util.evaluateJSONataExpression(rule.to,msg);
expr = RED.util.prepareJSONataExpression(rule.to, node);
} catch(e3) {
throw new Error("Invalid expression");
throw new Error("Invalid expression: " + e3.message);
}
return;
value = await new Promise(function(resolve, reject) {
RED.util.evaluateJSONataExpression(expr, msg, function(err, result) {
if (err) {
reject(new Error("Invalid expression: " + err.message));
} else {
resolve(result);
}
});
});
}
return value;
}
@@ -114,6 +142,7 @@ module.exports = function(RED) {
}
}
let cachedGetters = {};
for(let rule of node.rules) {
// [
// {
@@ -124,11 +153,10 @@ module.exports = function(RED) {
// }, ...
// ]
let cachedGetters = {};
if(rule.t === 'set') {
let value;
try {
value = getToValue(msg, rule);
value = await getToValue(msg, rule);
switch(rule.p) {
case "m.room.name":
await node.server.matrixClient.sendStateEvent(
@@ -184,11 +212,11 @@ module.exports = function(RED) {
if (typeof value !== 'object') {
setterErrors[rule.p] = "m.space.parent content must be object";
} else if (!msg.state_key) {
setterErrors[rule.p] = "m.space.parent required msg.state_key input to be set to the child roomId";
setterErrors[rule.p] = "m.space.parent required msg.state_key input to be set to the parent (space) roomId";
}else {
await node.server.matrixClient.sendStateEvent(
msg.topic,
"m.room.power_levels",
"m.space.parent",
value,
msg.state_key);
}
@@ -197,11 +225,11 @@ module.exports = function(RED) {
if (typeof value !== 'object') {
setterErrors[rule.p] = "m.space.child content must be object";
} else if (!msg.state_key) {
setterErrors[rule.p] = "m.space.child required msg.state_key input to be set to the parent roomId";
setterErrors[rule.p] = "m.space.child required msg.state_key input to be set to the child roomId";
}else {
await node.server.matrixClient.sendStateEvent(
msg.topic,
"m.room.power_levels",
"m.space.child",
value,
msg.state_key);
}
@@ -230,44 +258,53 @@ module.exports = function(RED) {
} catch(e) {
setterErrors[rule.p] = e.message;
}
// a later getter must not return what was cached before this set
cachedGetters = {};
} else if(rule.t === 'get') {
let value;
if(cachedGetters.hasOwnProperty(rule.p)) {
value = cachedGetters[rule.p];
let value,
// only the space events are keyed by another room;
// every other state event uses an empty state key
stateKey = (rule.p === 'm.space.parent' || rule.p === 'm.space.child') ? (msg.state_key || "") : "",
cacheKey = rule.p + "|" + stateKey;
if(cachedGetters.hasOwnProperty(cacheKey)) {
value = cachedGetters[cacheKey];
setToValue(value, rule);
} else {
try {
if(rule.ls) {
// we opted to lookup from local storage, will fallback to server if necessary
let room = node.server.matrixClient.getRoom(msg.topic);
if(room) {
value = await room.getLiveTimeline().getState("f").getStateEvents(rule.p, "");
let stateEvent = room ? room.getLiveTimeline().getState("f").getStateEvents(rule.p, stateKey) : null;
if(stateEvent) {
// the content, like the server lookup below (not the SDK's MatrixEvent)
value = stateEvent.getContent();
}
}
if(!value) {
// fetch the latest state event by type from server
value = await node.server.matrixClient.getStateEvent(msg.topic, rule.p, "");
if(value) {
// normalize some simpler events for easier access
switch(rule.p) {
case "m.room.name":
value = value?.name
break;
case "m.room.topic":
value = value?.topic
break;
case "m.room.avatar":
value = value?.url
break;
case "m.room.guest_access":
value = value?.guest_access;
break;
}
value = await node.server.matrixClient.getStateEvent(msg.topic, rule.p, stateKey);
}
if(value) {
// normalize some simpler events for easier access
switch(rule.p) {
case "m.room.name":
value = value?.name
break;
case "m.room.topic":
value = value?.topic
break;
case "m.room.avatar":
value = value?.url
break;
case "m.room.guest_access":
value = value?.guest_access;
break;
}
}
setToValue(value, rule);
cachedGetters[rule.p] = value;
cachedGetters[cacheKey] = value;
} catch(e) {
getterErrors[rule.p] = e;
getterErrors[rule.p] = (e && e.message) || String(e);
}
}
+10 -19
View File
@@ -7,7 +7,6 @@ module.exports = function(RED) {
this.name = n.name;
this.server = RED.nodes.getNode(n.server);
this.roomId = n.roomId;
this.contentType = n.contentType;
if (!node.server) {
node.warn("No configuration node");
@@ -17,21 +16,24 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
node.warn("No matrix server selected");
msg.error = "No matrix server selected";
node.error(msg.error, msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -39,30 +41,19 @@ module.exports = function(RED) {
let roomId = node.roomId || msg.topic;
if(!roomId) {
node.error("msg.topic is required. Specify in the input or configure the room ID on the node.", msg);
msg.error = "msg.topic is required. Specify in the input or configure the room ID on the node.";
node.error(msg.error, msg);
node.send([null, msg]);
return;
}
let queryParams = {
'from': msg.from || 0,
'limit': msg.limit || 100
};
if(msg.guests) {
queryParams['guests'] = msg.guests;
}
if(msg.order_by) {
queryParams['order_by'] = msg.order_by;
}
node.server.matrixClient
.getJoinedRoomMembers(roomId)
.then(function(e){
msg.payload = e;
node.send([msg, null]);
}).catch(function(e){
node.warn("Error fetching room user list " + e);
node.error("Error fetching room user list " + e, msg);
msg.error = e;
node.send([null, msg]);
});
+4 -4
View File
@@ -75,7 +75,7 @@
<script type="text/html" data-help-name="matrix-send-file">
<h3>Details</h3>
<p>This node will send a file to a Matrix chat room. Supports direct linking to a File In node.</p>
<p>This node will send a file to a Matrix chat room. Supports direct linking to a File In node. The file name, MIME type and size are included in the message so clients can name and open the download. The file is uploaded unencrypted; to send encrypted media into an encrypted room use the Upload File node (with <code>msg.encrypted</code>) followed by Send Message.</p>
<h3>Inputs</h3>
<dl class="message-properties">
@@ -97,17 +97,17 @@
<dt class="optional">msg.body
<span class="property-type">string | null</span>
</dt>
<dd> this will be the display name the client will see when rendered in their chat client. If this is left empty it will just display as "Attachment".</dd>
<dd> this will be the display name (caption) the client will see when rendered in their chat client. If this is left empty the file name is used. The file name is always sent as the download name.</dd>
<dt class="optional">msg.contentType
<span class="property-type">string | null</span>
</dt>
<dd> Content <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types" target="_blank">MIME Type</a>. Optional but highly recommended (so the client receiving knows what type of file it is).</dd>
<dd> Content <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types" target="_blank">MIME Type</a>. Overridden if configured on the node. If neither is set it is detected from <code>msg.filename</code>.</dd>
<dt class="optional">msg.content
<span class="property-type">object | null</span>
</dt>
<dd> craft your own msg.content to send to the server. If defined then <code>msg.filename</code>, <code>msg.contentType</code>, <code>msg.body</code>, and <code>msg.payload</code> aren't required since the file already exists.</dd>
<dd> craft your own msg.content to send to the server (used only when <code>msg.type</code> is <code>m.file</code>). If defined then <code>msg.filename</code>, <code>msg.contentType</code>, <code>msg.body</code>, and <code>msg.payload</code> aren't required since the file already exists.</dd>
</dl>
<h3>Outputs</h3>
+103 -64
View File
@@ -17,84 +17,123 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
node.warn("No matrix server selected");
return;
}
function sendError(text, msg, error) {
node.error(text, msg);
msg.error = error || text;
node.send([null, msg]);
}
if(!node.server.isConnected()) {
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
// Read a ReadStream or Blob payload into a Buffer. Node's fetch cannot
// upload a stream without the "duplex" option, which the SDK does not
// set, so streams used to fail with "duplex option is required".
async function toUploadable(payload) {
if (payload && typeof payload.pipe === 'function' && typeof payload.on === 'function') {
let chunks = [];
for await (const chunk of payload) {
chunks.push(Buffer.from(chunk));
}
return Buffer.concat(chunks);
}
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
node.warn("Room must be specified in msg.topic or in configuration");
return;
if (payload && !Buffer.isBuffer(payload) && typeof payload.arrayBuffer === 'function') {
return Buffer.from(await payload.arrayBuffer());
}
return payload;
}
if(msg.content && msg.type === 'm.file') {
node.server.matrixClient.sendMessage(msg.topic, msg.content)
.then(function(e) {
node.on("input", async function (msg) {
try {
if (! node.server || ! node.server.matrixClient) {
sendError("No matrix server selected", msg);
return;
}
if(!node.server.isConnected()) {
sendError("Matrix server connection is currently closed", msg);
return;
}
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
sendError("Room must be specified in msg.topic or in configuration", msg);
return;
}
if(msg.content && msg.type === 'm.file') {
try {
let e = await node.server.matrixClient.sendMessage(msg.topic, msg.content);
node.log("File message sent: " + e);
msg.eventId = e.event_id;
node.send([msg, null]);
})
.catch(function(e){
node.warn("Error sending file message " + e);
msg.error = e;
node.send([null, msg]);
});
return;
}
} catch(e) {
sendError("Error sending file message: " + e, msg, e);
}
return;
}
if(!msg.payload) {
node.error('msg.payload is required', msg);
return;
}
if(!msg.payload) {
sendError('msg.payload is required', msg);
return;
}
msg.contentType = node.contentType || msg.contentType || null;
node.log("Uploading file " + msg.filename);
node.server.matrixClient.uploadContent(
msg.payload, {
name: msg.filename || null, // Name to give the file on the server.
rawResponse: false, // Return the raw body, rather than parsing the JSON.
type: msg.contentType, // Content-type for the upload. Defaults to file.type, or applicaton/octet-stream.
onlyContentUri: false // Just return the content URI, rather than the whole body. Defaults to false. Ignored if opts.rawResponse is true.
})
.then(function(file){
const content = {
msgtype: 'm.file',
url: file.content_uri,
body: msg.body || "",
};
node.server.matrixClient
.sendMessage(msg.topic, content)
.then(function(e) {
node.log("File message sent: " + e);
msg.eventId = e.event_id;
node.send([msg, null]);
})
.catch(function(e){
node.warn("Error sending file message " + e);
msg.error = e;
node.send([null, msg]);
});
}).catch(function(e){
node.warn("Error uploading file message " + e);
msg.error = e;
node.send([null, msg]);
});
let payload = await toUploadable(msg.payload);
// The file name and type go in the event too (#88): clients use
// body/filename as the download name and info.mimetype to open
// the file. Without them e.g. a PDF arrived as a nameless blob.
const Mime = (await import('mime')).default;
msg.contentType = node.contentType
|| msg.contentType
|| (msg.filename && Mime.getType(msg.filename))
|| null;
let info = {};
if (msg.contentType) {
info.mimetype = msg.contentType;
}
if (Buffer.isBuffer(payload) || typeof payload === 'string') {
info.size = Buffer.byteLength(payload);
}
node.log("Uploading file " + msg.filename);
let file;
try {
file = await node.server.matrixClient.uploadContent(
payload, {
name: msg.filename || undefined, // Name to give the file on the server.
type: msg.contentType || undefined, // Content-type for the upload. Defaults to applicaton/octet-stream.
});
} catch(e) {
sendError("Error uploading file message: " + e, msg, e);
return;
}
const content = {
msgtype: 'm.file',
url: file.content_uri,
body: msg.body || msg.filename || "file",
info: info,
};
if (msg.filename) {
content.filename = msg.filename;
}
try {
let e = await node.server.matrixClient.sendMessage(msg.topic, content);
node.log("File message sent: " + e);
msg.eventId = e.event_id;
node.send([msg, null]);
} catch(e) {
sendError("Error sending file message: " + e, msg, e);
}
} catch(e) {
sendError("Error sending file: " + e, msg, e);
}
});
node.on("close", function() {
@@ -102,4 +141,4 @@ module.exports = function(RED) {
});
}
RED.nodes.registerType("matrix-send-file", MatrixSendFile);
}
}
+10 -4
View File
@@ -75,7 +75,7 @@
<script type="text/html" data-help-name="matrix-send-image">
<h3>Details</h3>
<p>This node will send an image to a Matrix chat room. Supports direct linking to a File In node. It's recommended you set <code>msg.contentType</code> so the client knows how to render the image (otherwise the image could show blank).</p>
<p>This node will send an image to a Matrix chat room. Supports direct linking to a File In node. The MIME type, size and width/height are filled in automatically (from the image data, or the file name), so clients and bridges render it as an image. The image is uploaded unencrypted; to send encrypted media into an encrypted room use the Upload File node (with <code>msg.encrypted</code>) followed by Send Message.</p>
<h3>Inputs</h3>
<dl class="message-properties">
@@ -97,17 +97,17 @@
<dt class="optional">msg.body
<span class="property-type">string | null</span>
</dt>
<dd> this will be the display name the client will see when rendered in their chat client. If this is left empty it will just display as "Attachment".</dd>
<dd> this will be the display name (caption) the client will see when rendered in their chat client. If this is left empty the file name is used, or "Image" without one.</dd>
<dt class="optional">msg.contentType
<span class="property-type">string | null</span>
</dt>
<dd> Content <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types" target="_blank">MIME Type</a>. Overridden if configured on the node. Optional but highly recommended (so the client receiving knows what type of file it is).</dd>
<dd> Content <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types" target="_blank">MIME Type</a>. Overridden if configured on the node. If neither is set it is detected from the image data, then from <code>msg.filename</code>.</dd>
<dt class="optional">msg.content
<span class="property-type">object | null</span>
</dt>
<dd> craft your own msg.content to send to the server. If defined then <code>msg.filename</code>, <code>msg.contentType</code>, <code>msg.body</code>, and <code>msg.payload</code> aren't required since the file already exists.</dd>
<dd> craft your own msg.content to send to the server (used only when <code>msg.type</code> is <code>m.image</code>). If defined then <code>msg.filename</code>, <code>msg.contentType</code>, <code>msg.body</code>, and <code>msg.payload</code> aren't required since the file already exists.</dd>
</dl>
<h3>Outputs</h3>
@@ -116,6 +116,12 @@
<dl class="message-properties">
<dt>msg.eventId <span class="property-type">string</span></dt>
<dd>the eventId from the posted message.</dd>
<dt>msg.content_uri_mxc <span class="property-type">string</span></dt>
<dd>the mxc:// URI of the uploaded image.</dd>
<dt>msg.content_uri <span class="property-type">string</span></dt>
<dd>an HTTP download URL for the uploaded image. Homeservers with authenticated media require an <code>Authorization: Bearer &lt;access token&gt;</code> header to download it.</dd>
</dl>
</li>
<li>Error
+124 -67
View File
@@ -1,3 +1,5 @@
const { imageSize } = require('image-size');
module.exports = function(RED) {
function MatrixSendImage(n) {
RED.nodes.createNode(this, n);
@@ -17,88 +19,143 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
node.warn("No matrix server selected");
return;
}
function sendError(text, msg, error) {
node.error(text, msg);
msg.error = error || text;
node.send([null, msg]);
}
if(!node.server.isConnected()) {
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
// Read a ReadStream or Blob payload into a Buffer. Node's fetch cannot
// upload a stream without the "duplex" option, which the SDK does not
// set, so streams used to fail with "duplex option is required".
async function toUploadable(payload) {
if (payload && typeof payload.pipe === 'function' && typeof payload.on === 'function') {
let chunks = [];
for await (const chunk of payload) {
chunks.push(Buffer.from(chunk));
}
return Buffer.concat(chunks);
}
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
node.warn("Room must be specified in msg.topic or in configuration");
return;
if (payload && !Buffer.isBuffer(payload) && typeof payload.arrayBuffer === 'function') {
return Buffer.from(await payload.arrayBuffer());
}
return payload;
}
if(msg.content && msg.type === 'm.image') {
node.server.matrixClient.sendMessage(msg.topic, msg.content)
.then(function(e) {
node.on("input", async function (msg) {
try {
if (! node.server || ! node.server.matrixClient) {
sendError("No matrix server selected", msg);
return;
}
if(!node.server.isConnected()) {
sendError("Matrix server connection is currently closed", msg);
return;
}
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
sendError("Room must be specified in msg.topic or in configuration", msg);
return;
}
if(msg.content && msg.type === 'm.image') {
try {
let e = await node.server.matrixClient.sendMessage(msg.topic, msg.content);
node.log("Image message sent: " + e);
msg.eventId = e.event_id;
node.send([msg, null]);
})
.catch(function(e){
node.warn("Error sending image message " + e);
msg.error = e;
node.send([null, msg]);
});
return;
}
} catch(e) {
sendError("Error sending image message: " + e, msg, e);
}
return;
}
if(!msg.payload) {
node.error('msg.payload is required', msg);
return;
}
if(!msg.payload) {
sendError('msg.payload is required', msg);
return;
}
msg.contentType = node.contentType || msg.contentType || null;
node.log("Uploading image " + msg.filename);
node.server.matrixClient.uploadContent(
msg.payload, {
name: msg.filename || null, // Name to give the file on the server.
rawResponse: false, // Return the raw body, rather than parsing the JSON.
type: msg.contentType, // Content-type for the upload. Defaults to file.type, or applicaton/octet-stream.
onlyContentUri: false // Just return the content URI, rather than the whole body. Defaults to false. Ignored if opts.rawResponse is true.
})
.then(function(file){
node.server.matrixClient
.sendImageMessage(
msg.topic,
file.content_uri,
{},
(msg.body || msg.filename) || null,
null
)
.then(function(e) {
node.log("Image message sent: " + e);
msg.eventId = e.event_id;
msg.content_uri_mxc = file.content_uri;
msg.content_uri = node.server.matrixClient.mxcUrlToHttp(file.content_uri);
node.send([msg, null]);
})
.catch(function(e){
node.warn("Error sending image message: " + e);
msg.error = e;
node.send([null, msg]);
let payload = await toUploadable(msg.payload);
// Fill in content.info (#80): clients and bridges (e.g. mautrix)
// need at least the mimetype to render the image instead of
// offering a binary download. Detect from the image bytes,
// falling back to the file name.
const Mime = (await import('mime')).default;
let dimensions = null;
if (Buffer.isBuffer(payload)) {
try {
dimensions = imageSize(payload);
} catch(e) {
dimensions = null; // not an image format image-size knows
}
}
msg.contentType = node.contentType
|| msg.contentType
|| (dimensions && dimensions.type && Mime.getType(dimensions.type))
|| (msg.filename && Mime.getType(msg.filename))
|| null;
let info = {};
if (msg.contentType) {
info.mimetype = msg.contentType;
}
if (Buffer.isBuffer(payload) || typeof payload === 'string') {
info.size = Buffer.byteLength(payload);
}
if (dimensions && dimensions.width && dimensions.height) {
info.w = dimensions.width;
info.h = dimensions.height;
}
node.log("Uploading image " + msg.filename);
let file;
try {
file = await node.server.matrixClient.uploadContent(
payload, {
name: msg.filename || undefined, // Name to give the file on the server.
type: msg.contentType || undefined, // Content-type for the upload. Defaults to applicaton/octet-stream.
});
})
.catch(function(e){
node.warn("Error uploading image message: " + e);
msg.error = e;
node.send([null, msg]);
});
} catch(e) {
sendError("Error uploading image message: " + e, msg, e);
return;
}
let content = {
msgtype: 'm.image',
url: file.content_uri,
body: msg.body || msg.filename || "Image",
info: info,
};
if (msg.filename) {
content.filename = msg.filename;
}
try {
let e = await node.server.matrixClient.sendMessage(msg.topic, content);
node.log("Image message sent: " + e);
msg.eventId = e.event_id;
msg.content_uri_mxc = file.content_uri;
// Authenticated media URL (the legacy unauthenticated one
// 404s on homeservers with authenticated media); downloads
// need an "Authorization: Bearer <token>" header.
msg.content_uri = node.server.matrixClient.mxcUrlToHttp(file.content_uri, undefined, undefined, undefined, false, true, true)
|| node.server.matrixClient.mxcUrlToHttp(file.content_uri);
node.send([msg, null]);
} catch(e) {
sendError("Error sending image message: " + e, msg, e);
}
} catch(e) {
sendError("Error sending image: " + e, msg, e);
}
});
node.on("close", function() {
@@ -106,4 +163,4 @@ module.exports = function(RED) {
});
}
RED.nodes.registerType("matrix-send-image", MatrixSendImage);
}
}
+3 -1
View File
@@ -194,7 +194,9 @@
read from <code>msg.*</code> using the documented names so the simple
case <em>just works</em> &mdash; reach for the type selector when you
want to pull from a flow / global variable or pin a static value on
the node itself.
the node itself. An empty <code>str</code> or <code>num</code> value
means "not provided", so the optional field is left out (or its
default is generated).
</p>
<h4>Configuration</h4>
+49 -19
View File
@@ -17,22 +17,45 @@ module.exports = function(RED) {
// Dynamic inputs: each has a `*Type` (msg | flow | global | str | num)
// and a `*Value` (the property path or literal). Defaults preserve the
// documented per-message names so existing flows keep working.
this.latitudeType = n.latitudeType || "msg";
this.latitudeValue = n.latitudeValue || "latitude";
this.longitudeType = n.longitudeType || "msg";
this.longitudeValue = n.longitudeValue || "longitude";
this.altitudeType = n.altitudeType || "msg";
this.altitudeValue = n.altitudeValue || "altitude";
this.geoUriType = n.geoUriType || "msg";
this.geoUriValue = n.geoUriValue || "geo_uri";
this.descriptionType = n.descriptionType || "msg";
this.descriptionValue = n.descriptionValue || "description";
this.assetTypeType = n.assetTypeType || "msg";
this.assetTypeValue = n.assetTypeValue || "assetType";
this.timestampType = n.timestampType || "msg";
this.timestampValue = n.timestampValue || "timestamp";
this.textType = n.textType || "msg";
this.textValue = n.textValue || "payload";
//
// The default name is only used when the setting is missing (older
// configs) or a msg property is left blank. An empty str/num literal
// means "not provided"; it used to be replaced by the default *name*,
// so e.g. the text "geo_uri" was sent as the geo URI and an empty
// asset type failed as "assetType".
function typedSetting(type, value, defaultValue) {
type = type || "msg";
if (value === undefined || value === null || (value === "" && type === "msg")) {
value = defaultValue;
}
return { type: type, value: value };
}
const settings = {
latitude: typedSetting(n.latitudeType, n.latitudeValue, "latitude"),
longitude: typedSetting(n.longitudeType, n.longitudeValue, "longitude"),
altitude: typedSetting(n.altitudeType, n.altitudeValue, "altitude"),
geoUri: typedSetting(n.geoUriType, n.geoUriValue, "geo_uri"),
description: typedSetting(n.descriptionType, n.descriptionValue, "description"),
assetType: typedSetting(n.assetTypeType, n.assetTypeValue, "assetType"),
timestamp: typedSetting(n.timestampType, n.timestampValue, "timestamp"),
text: typedSetting(n.textType, n.textValue, "payload"),
};
this.latitudeType = settings.latitude.type;
this.latitudeValue = settings.latitude.value;
this.longitudeType = settings.longitude.type;
this.longitudeValue = settings.longitude.value;
this.altitudeType = settings.altitude.type;
this.altitudeValue = settings.altitude.value;
this.geoUriType = settings.geoUri.type;
this.geoUriValue = settings.geoUri.value;
this.descriptionType = settings.description.type;
this.descriptionValue = settings.description.value;
this.assetTypeType = settings.assetType.type;
this.assetTypeValue = settings.assetType.value;
this.timestampType = settings.timestamp.type;
this.timestampValue = settings.timestamp.value;
this.textType = settings.text.type;
this.textValue = settings.text.value;
if (!node.server) {
node.warn("No configuration node");
@@ -41,10 +64,10 @@ module.exports = function(RED) {
node.server.register(node);
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function() {
node.server.listen(node, "disconnected", function() {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
@@ -90,10 +113,13 @@ module.exports = function(RED) {
node.on("input", async function(msg) {
if (!node.server || !node.server.matrixClient) {
node.warn("No matrix server selected");
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if (!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -101,7 +127,9 @@ module.exports = function(RED) {
msg.topic = node.roomId || msg.topic;
if (!msg.topic) {
msg.error = "Room must be specified in msg.topic or in configuration";
node.error("Room must be specified in msg.topic or in configuration", msg);
node.send([null, msg]);
return;
}
@@ -130,6 +158,7 @@ module.exports = function(RED) {
const lat = parseFloat(rawLat);
const lng = parseFloat(rawLng);
if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
msg.error = "Latitude and longitude (numbers) - or a geo_uri - are required";
node.error("Latitude and longitude (numbers) - or a geo_uri - are required", msg);
node.send([null, msg]);
return;
@@ -148,6 +177,7 @@ module.exports = function(RED) {
if (!isEmpty(rawAlt)) {
const alt = parseFloat(rawAlt);
if (!Number.isFinite(alt)) {
msg.error = "Altitude must be a number when provided";
node.error("Altitude must be a number when provided", msg);
node.send([null, msg]);
return;
+40 -26
View File
@@ -60,16 +60,32 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
function sendError(text, msg, error) {
node.error(text, msg);
msg.error = error || text;
node.send([null, msg]);
}
// Make the input handler async so we can await the dynamic import.
node.on("input", async function (msg) {
// An exception escaping this async handler would be an unhandled
// rejection (which takes Node-RED down), so report it instead.
try {
await onInput(msg);
} catch(e) {
sendError("Error sending message: " + (e && e.message || e), msg, e);
}
});
async function onInput(msg) {
// Await the SDK import and get the RelationType constant.
const sdk = await sdkPromise;
const RelationType = sdk.RelationType;
@@ -97,25 +113,24 @@ module.exports = function(RED) {
threadReply = getToValue(msg, node.threadReplyType, node.threadReplyValue);
if (!node.server || !node.server.matrixClient) {
node.warn("No matrix server selected");
sendError("No matrix server selected", msg);
return;
}
if(!node.server.isConnected()) {
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
sendError("Matrix server connection is currently closed", msg);
return;
}
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
node.warn("Room must be specified in msg.topic or in configuration");
sendError("Room must be specified in msg.topic or in configuration", msg);
return;
}
let payload = n.message || msg.payload;
if(!payload) {
node.error('msg.payload must be defined or the message configured on the node.', msg);
sendError('msg.payload must be defined or the message configured on the node.', msg);
return;
}
@@ -125,7 +140,7 @@ module.exports = function(RED) {
} else {
if (msgType === 'msg.type') {
if (!msg.type) {
node.error("msg.type is set to be passed in via msg.type but was not defined", msg);
sendError("msg.type is set to be passed in via msg.type but was not defined", msg);
return;
}
msgType = msg.type;
@@ -133,7 +148,7 @@ module.exports = function(RED) {
if (msgFormat === 'msg.format') {
if (!Object.hasOwn(msg, 'format')) {
node.error("Message format is set to be passed in via msg.format but was not defined", msg);
sendError("Message format is set to be passed in via msg.format but was not defined", msg);
return;
}
msgFormat = msg.format;
@@ -152,14 +167,16 @@ module.exports = function(RED) {
// rendered HTML as `formatted_body` and keep the original
// markdown source as `body` (matrix spec convention for
// formatted messages). If the message turns out to be
// plain text and contains backslash escapes, strip those
// from `body` and send no HTML; otherwise leave `body`
// as the original payload.
// plain text and contains backslash escapes, send the
// unescaped text as HTML (toPlaintext() returns
// HTML-escaped text, so it must not go into `body`, where
// "&" would show up as "&amp;"); `body` stays the source.
const source = payload.toString();
const md = new Markdown(source);
if (md.isPlainText()) {
if (source.indexOf("\\") > -1) {
content.body = md.toPlaintext();
content.format = "org.matrix.custom.html";
content.formatted_body = md.toPlaintext();
}
} else {
content.format = "org.matrix.custom.html";
@@ -211,19 +228,16 @@ module.exports = function(RED) {
}
}
node.server.matrixClient.sendMessage(msg.topic, content)
.then(function(e) {
node.log("Message sent: " + payload);
msg.eventId = e.event_id;
node.log(JSON.stringify(e));
node.send([msg, null]);
})
.catch(function(e){
node.error("Error sending message: " + e, {});
msg.error = e;
node.send([null, msg]);
});
});
try {
let e = await node.server.matrixClient.sendMessage(msg.topic, content);
node.log("Message sent: " + payload);
msg.eventId = e.event_id;
node.log(JSON.stringify(e));
node.send([msg, null]);
} catch(e) {
sendError("Error sending message: " + e, msg, e);
}
}
node.on("close", function() {
node.server.deregister(node);
+181 -3
View File
@@ -36,9 +36,11 @@
defaults: {
name: { value: null },
autoAcceptRoomInvites: { value: true },
enableE2ee: { type: "checkbox", value: true },
global: { type: "checkbox", value: true },
allowUnknownDevices: { type: "checkbox", value: true }
// no "type" here: in defaults, "type" marks a reference to a config
// node, so the editor showed these as undefined in the Info panel
enableE2ee: { value: true },
global: { value: true },
allowUnknownDevices: { value: true }
},
icon: "matrix.png",
label: function() {
@@ -204,6 +206,147 @@
$("#matrix-sb-overlay").data("sbStatusFn")();
});
// --- Clear encryption data (modal dialog) ---
// Destructive, so the user must type "delete" before Confirm is
// enabled. Reuses the secure backup modal's styles (built above).
// After clearing, the node stays disconnected ("encryption hold")
// until the bot logs in as a new session; the dialog then walks
// the user through that.
if (!document.getElementById("matrix-ce-overlay")) {
$('<style>'
+ '.matrix-ce-danger{background:#c9302c !important;border-color:#ac2925 !important;color:#fff !important;}'
+ '.matrix-ce-danger:disabled{opacity:.5;cursor:not-allowed;}'
+ '.matrix-ce-list{margin:8px 0 0 18px;padding:0;font-size:13px;line-height:1.6;}'
+ '.matrix-ce-steps{margin:10px 0 0 20px;padding:0;font-size:13px;line-height:1.7;}'
+ '</style>').appendTo("head");
$('<div id="matrix-ce-overlay" class="matrix-sb-overlay"><div class="matrix-sb-modal">'
+ '<div class="matrix-sb-head"><span><i class="fa fa-trash"></i> Clear Encryption Data</span>'
+ '<span class="matrix-sb-x" id="matrix-ce-x" title="Close">&times;</span></div>'
+ '<div class="matrix-sb-body">'
+ '<div id="matrix-ce-form">'
+ '<div class="matrix-sb-warn"><b>This cannot be undone.</b> It deletes this bot\'s local encryption store:'
+ '<ul class="matrix-ce-list">'
+ '<li>Messages that were already received encrypted can no longer be decrypted.</li>'
+ '<li>The Matrix client is disconnected and stays disconnected, even after deploys and restarts, until the bot logs in as a new session.</li>'
+ '<li>Other users and sessions will need to verify the bot\'s new session.</li>'
+ '</ul></div>'
+ 'Only do this if encryption fails to start (for example a corrupted encryption store after an update).'
+ '<div class="matrix-sb-section">'
+ '<label for="matrix-ce-confirm-input">Type <code>delete</code> to confirm</label>'
+ '<input type="text" id="matrix-ce-confirm-input" autocomplete="off" spellcheck="false" placeholder="delete">'
+ '</div>'
+ '</div>'
+ '<div id="matrix-ce-next" style="display:none;">'
+ '<div class="matrix-sb-state"><i class="fa fa-check-circle" style="color:#3a9a4e;font-size:18px;"></i>'
+ '<span><b>Encryption data deleted.</b> The Matrix client is disconnected and will stay disconnected, '
+ 'even after deploys and restarts, until the bot logs in as a new session. '
+ 'Reconnecting with the old session is not possible: the homeserver rejects its regenerated keys.</span></div>'
+ '<div class="matrix-sb-section"><label>Next steps</label>'
+ '<ol class="matrix-ce-steps">'
+ '<li>Enter the bot\'s password and click <b>Update Access Token</b> to log in as a new session.</li>'
+ '<li>Click <b>Update</b>, then <b>Deploy</b>. The client connects with a fresh encryption store.</li>'
+ '<li>Once connected, remove the old session <code id="matrix-ce-old-device"></code> in <b>Manage sessions</b>.</li>'
+ '</ol></div>'
+ '</div>'
+ '<div class="matrix-sb-result" id="matrix-ce-result" style="display:none;"></div>'
+ '</div>'
+ '<div class="matrix-sb-foot">'
+ '<button type="button" class="red-ui-button" id="matrix-ce-cancel">Cancel</button>'
+ '<button type="button" class="red-ui-button matrix-ce-danger" id="matrix-ce-confirm" disabled>Confirm</button>'
+ '<button type="button" class="red-ui-button primary" id="matrix-ce-goto-login" style="display:none;">Go to login</button>'
+ '</div></div></div>').appendTo(document.body);
var ceEsc = function(s) { return $("<div>").text(s == null ? "" : String(s)).html(); };
var ceClose = function() { $("#matrix-ce-overlay").fadeOut(120); };
var ceTyped = function() { return $("#matrix-ce-confirm-input").val().trim().toLowerCase() === "delete"; };
var ceResult = function(ok, text) {
$("#matrix-ce-result").removeClass("ok err").addClass(ok ? "ok" : "err").html(ceEsc(text)).show();
};
var ceRetry = function() {
$("#matrix-ce-confirm-input").prop("disabled", false);
$("#matrix-ce-confirm").prop("disabled", !ceTyped());
};
$("#matrix-ce-x,#matrix-ce-cancel").on("click", ceClose);
$("#matrix-ce-overlay").on("mousedown", function(e) { if (e.target === this) { ceClose(); } });
$(document).on("keydown.matrixce", function(e) {
if (e.key === "Escape" && $("#matrix-ce-overlay").is(":visible")) { ceClose(); }
});
$("#matrix-ce-confirm-input").on("input", function() {
$("#matrix-ce-confirm").prop("disabled", !ceTyped());
}).on("keydown", function(e) {
if (e.key === "Enter" && ceTyped()) { $("#matrix-ce-confirm").trigger("click"); }
});
$("#matrix-ce-confirm").on("click", function() {
if (!ceTyped()) { return; }
$("#matrix-ce-confirm,#matrix-ce-confirm-input").prop("disabled", true);
$("#matrix-ce-result").removeClass("ok err").text("Clearing encryption data…").show();
$.ajax({
url: "matrix-chat/clear-encryption-data", type: "POST",
contentType: "application/json",
data: JSON.stringify({ id: $("#matrix-ce-overlay").data("matrixNodeId"), action: "clear", confirmDelete: true }),
}).done(function(data) {
if (data.result !== "ok") {
ceResult(false, data.message || "Unknown error");
ceRetry();
return;
}
$("#matrix-ce-form,#matrix-ce-result,#matrix-ce-confirm").hide();
$("#matrix-ce-old-device").text(data.deviceId || "(unknown)");
$("#matrix-ce-next,#matrix-ce-goto-login").show();
$("#matrix-ce-cancel").text("Close");
var refresh = $("#matrix-ce-overlay").data("ceRefreshHold");
if (refresh) { refresh(); }
}).fail(function() {
ceResult(false, "Request failed. Is Node-RED still running?");
ceRetry();
});
});
$("#matrix-ce-goto-login").on("click", function() {
ceClose();
var pw = $("#node-config-input-password");
if (pw.length) {
pw[0].scrollIntoView({ block: "center" });
setTimeout(function() { pw.trigger("focus"); }, 150);
}
});
}
// Show whether this node is on an encryption hold (data cleared,
// waiting for a new session), so the way forward is visible even
// after the dialog was closed or Node-RED restarted.
var ceRefreshHold = function() {
$.ajax({
url: "matrix-chat/clear-encryption-data", type: "POST",
contentType: "application/json",
data: JSON.stringify({ id: nodeId, action: "status" }),
}).done(function(data) {
var notice = $("#matrix-ce-hold-notice");
if (data.result !== "ok" || !data.hold) { notice.hide(); return; }
var when = data.hold.clearedAt ? new Date(data.hold.clearedAt).toLocaleString() : "earlier";
notice.html(
'<i class="fa fa-pause-circle"></i> <b>Disconnected: encryption data was cleared</b> (' + $("<div>").text(when).html() + ') '
+ 'for session <code>' + $("<div>").text(data.hold.deviceId || "(unknown)").html() + '</code>. '
+ 'The client stays disconnected until the bot logs in as a new session: enter the password above, click '
+ '<b>Update Access Token</b>, then <b>Update</b> and <b>Deploy</b>.'
).show();
}).fail(function() { $("#matrix-ce-hold-notice").hide(); });
};
$("#matrix-ce-overlay").data("ceRefreshHold", ceRefreshHold);
ceRefreshHold();
$("#matrix-clear-encryption-btn").on("click", function() {
// reset the dialog every time it is opened
$("#matrix-ce-form").show();
$("#matrix-ce-next,#matrix-ce-goto-login,#matrix-ce-result").hide();
$("#matrix-ce-confirm-input").val("").prop("disabled", false);
$("#matrix-ce-confirm").prop("disabled", true).show();
$("#matrix-ce-cancel").text("Cancel");
$("#matrix-ce-overlay").data("matrixNodeId", nodeId).fadeIn(120);
setTimeout(function() { $("#matrix-ce-confirm-input").trigger("focus"); }, 150);
});
// --- Verification list (modal) ---
// Built once and reused; the node id is stored on the overlay.
if (!document.getElementById("matrix-vl-overlay")) {
@@ -923,6 +1066,18 @@
View the account's logged-in sessions, verify them, or remove ones you don't recognize.
The server configuration must be deployed and connected first.
</div>
<div class="form-row">
<label><i class="fa fa-trash"></i> Encryption</label>
<button type="button" class="red-ui-button" id="matrix-clear-encryption-btn">Clear encryption data</button>
</div>
<div class="form-tips" style="margin-bottom: 12px;">
Deletes the bot's local encryption store. Only use this if encryption fails to start
(for example a corrupted store after an update). Previously received encrypted messages
can no longer be decrypted, and the bot must then log in as a new session before it reconnects.
The server configuration must be deployed first.
</div>
<div class="form-tips" id="matrix-ce-hold-notice" style="display:none;margin-bottom: 12px;color:#7a5b16;background-color:#fdf3e7;border-color:#f0c36d;"></div>
</script>
<script type="text/html" data-help-name="matrix-server-config">
@@ -965,4 +1120,27 @@
(for example emailing the emoji for a human to confirm).
</p>
</div>
<h3>Clearing encryption data</h3>
<div>
<p>
If encryption fails to start (the node logs <em>Encryption initialization failed</em>,
for example because the encryption store was corrupted by an update), the fix is a fresh
encryption store under a <strong>new session</strong>. Logging in again with
<strong>Update Access Token</strong> and deploying does this on its own: a new session
always starts with a fresh store.
</p>
<p>
The <strong>Clear encryption data</strong> button (you must type <code>delete</code> to confirm)
also deletes the old store first. It disconnects the Matrix client and keeps it disconnected,
even across deploys and Node-RED restarts, until the bot logs in as a new session. Reconnecting
with the old session is not possible because the homeserver still holds that session's old keys
and rejects the regenerated ones. Once the new session is connected, remove the old one in
<strong>Manage sessions</strong>.
</p>
<p>
This cannot be undone: previously received encrypted messages can no longer be decrypted,
and other users and sessions will need to verify the bot's new session.
</p>
</div>
</script>
+486 -70
View File
@@ -1,6 +1,7 @@
// matrix-js-sdk is an ES module; load it via dynamic import so this CommonJS
// node keeps working. All SDK-dependent setup awaits this promise.
const sdkPromise = import("matrix-js-sdk");
const SYNC_GUARD = Symbol('node-red-contrib-matrix-chat.syncRequestGuard');
// The crypto-api enums (CryptoEvent, VerificationPhase, ...) are not re-exported
// from the package root, so they are imported from the crypto-api subpath.
const cryptoApiPromise = import("matrix-js-sdk/lib/crypto-api/index.js");
@@ -47,29 +48,83 @@ async function resolveHomeserverUrl(sdk, configuredUrl) {
if(!domain) {
return configuredUrl;
}
try {
const discovery = await sdk.AutoDiscovery.findClientConfig(domain);
const homeserver = discovery['m.homeserver'];
// Discovery forces https, so on hosts without an HTTPS .well-known (LAN
// IPs, localhost, plain http) it can wait for a 5 second timeout on every
// start. Check in parallel whether the configured URL already serves the
// client API: if it does, discovery only gets a short grace period to
// report a delegation. A delegation always wins when there is one.
const discovery = sdk.AutoDiscovery.findClientConfig(domain).then(function(result) {
const homeserver = result['m.homeserver'];
if(homeserver && homeserver.state === sdk.AutoDiscovery.SUCCESS && homeserver.base_url) {
return homeserver.base_url;
}
} catch(e) {
// discovery failed unexpectedly - fall back to the configured URL
return null;
}).catch(function() {
return null; // discovery failed unexpectedly - fall back to the configured URL
});
const servesClientApi = !/^https?:\/\//i.test(String(configuredUrl)) ? Promise.resolve(false) :
fetch(String(configuredUrl).replace(/\/+$/, '') + '/_matrix/client/versions', {
signal: AbortSignal.timeout(5000),
}).then(function(res) {
return res.ok ? res.json() : null;
}).then(function(body) {
return !!(body && Array.isArray(body.versions));
}).catch(function() {
return false; // not reachable as a homeserver
});
// an IP address or localhost cannot delegate, so do not wait for it
const canDelegate = !/^(localhost|[0-9.]+|\[[0-9a-f:.]+\])(:\d+)?$/i.test(domain);
const DISCOVERY_GRACE_MS = canDelegate ? 1000 : 0;
const first = await Promise.race([
discovery.then(function(url) { return { discovered: url }; }),
servesClientApi.then(function(ok) { return ok ? { servesClientApi: true } : discovery.then(function(url) { return { discovered: url }; }); }),
]);
if(first.discovered) {
return first.discovered;
}
if(first.servesClientApi) {
const delegated = await Promise.race([discovery, new Promise(function(r) { setTimeout(r, DISCOVERY_GRACE_MS, null); })]);
return delegated || configuredUrl;
}
return configuredUrl;
}
module.exports = function(RED) {
// disable logging if set to "off"
let loggingSettings = RED.settings.get('logging');
if(
typeof loggingSettings.console !== 'undefined' &&
typeof loggingSettings.console.level !== 'undefined' &&
['info','debug','trace'].indexOf(loggingSettings.console.level.toLowerCase()) >= 0
) {
import('matrix-js-sdk/lib/logger.js')
.then(({ logger }) => logger.disableAll())
.catch(() => { /* logger module path changed - ignore */ });
// matrix-js-sdk logs verbosely (debug level) on its own logger. Follow the
// Node-RED console level: SDK debug/info output only at debug or trace,
// warnings and errors at the matching levels. This used to be inverted:
// the SDK was silenced at "info" but flooded the console when the level
// was lowered to "warn"/"error"/"off".
let loggingSettings = RED.settings.get('logging') || {};
let consoleLevel = String(loggingSettings.console && loggingSettings.console.level || 'info').toLowerCase();
// lowest SDK method level still shown for each Node-RED level
let minSdkLevel = { off: 5, fatal: 4, error: 4, warn: 3, info: 3 }[consoleLevel];
if(minSdkLevel !== undefined) {
// logger.disableAll() on the SDK's root logger is not enough: every
// child logger (FetchHttpApi, MatrixRTCSession, ...) resets itself to
// DEBUG when created. Wrap the method factory of the loglevel instance
// the SDK uses instead. Only the SDK's own "matrix" loggers are
// filtered: loglevel can be shared with other modules.
sdkPromise.then(function() {
const loglevel = require('module').createRequire(require.resolve('matrix-js-sdk'))('loglevel');
const methodLevels = { trace: 0, debug: 1, log: 2, info: 2, warn: 3, error: 4 };
const isSdkLogger = function(name) { return typeof name === 'string' && /^matrix(-|$)/.test(name); };
const originalFactory = loglevel.methodFactory;
const filteredFactory = function(methodName, level, loggerName) {
let method = originalFactory.apply(this, arguments);
let methodLevel = methodLevels[methodName] !== undefined ? methodLevels[methodName] : 2;
return (isSdkLogger(loggerName) && methodLevel < minSdkLevel) ? function() {} : method;
};
// new loggers copy the root factory; existing SDK loggers are
// switched over here (their children copy it from them)
loglevel.methodFactory = filteredFactory;
Object.entries(loglevel.getLoggers()).forEach(function([name, l]) {
if(isSdkLogger(name)) {
l.methodFactory = filteredFactory;
l.rebuild();
}
});
}).catch(function() { /* logging internals changed - leave SDK logging as is */ });
}
function MatrixFolderNameFromUserId(name) {
@@ -120,8 +175,35 @@ module.exports = function(RED) {
node.register = function(consumerNode) {
node.users[consumerNode.id] = consumerNode;
};
// Listeners consumers attach to this node, so deregister() can remove
// them. Without this a consumer that is redeployed on its own
// ("Modified Nodes" deploy, this config node keeps running) left its
// old listeners behind: closed receive nodes kept forwarding every
// message, so each redeploy added another duplicate.
let consumerListeners = new Map(); // consumer id -> [[event, fn], ...]
node.listen = function(consumerNode, event, fn) {
node.on(event, fn);
if(!consumerListeners.has(consumerNode.id)) {
consumerListeners.set(consumerNode.id, []);
}
consumerListeners.get(consumerNode.id).push([event, fn]);
// A consumer created while we are already connected missed the
// "connected" event; replay it so its status is not stuck on
// "disconnected".
if(event === "connected" && node.connected === true) {
setImmediate(function() {
if(node.connected === true && consumerListeners.has(consumerNode.id)) {
fn();
}
});
}
};
node.deregister = function(consumerNode) {
delete node.users[consumerNode.id];
for(const [event, fn] of consumerListeners.get(consumerNode.id) || []) {
node.removeListener(event, fn);
}
consumerListeners.delete(consumerNode.id);
};
if(!this.userId) {
@@ -140,7 +222,21 @@ module.exports = function(RED) {
// multiple server-config nodes never collide.
let cryptoDbPrefix = 'mxjssdk-' + MatrixFolderNameFromUserId(this.userId),
cryptoSnapshotPath = null,
cryptoSnapshotInterval = null;
cryptoSnapshotInterval = null,
// Set once the encryption data has been cleared via the admin
// endpoint. Stops any further snapshot from writing the (deleted
// or recreated-empty) store back to disk before the redeploy.
cryptoCleared = false,
// Set once the Rust crypto stack is initialized. Until then the
// in-memory store may not be restored yet, and snapshotting it
// would overwrite the saved store on disk.
cryptoReady = false,
// Set when the node is closed. Startup is asynchronous (SDK import,
// homeserver discovery, /whoami, crypto init), so every step checks
// it: a node closed mid-startup (e.g. deployed again quickly) must
// not go on to start a client that then syncs forever unseen.
closing = false,
clientStarting = null; // promise of an in-progress startup (crypto init + startClient)
if(!this.credentials.accessToken) {
node.error("Matrix connection failed: missing access token in configuration.");
@@ -162,7 +258,7 @@ module.exports = function(RED) {
let stored_device_id = getStoredDeviceId(localStorage),
device_id = this.matrixClient.getDeviceId();
if(!device_id && node.enableE2ee) {
if(!device_id && node.e2ee) {
node.error("Failed to auto detect deviceId for this auth token. You will need to manually specify one. You may need to login to create a new deviceId.")
} else {
if(!stored_device_id || stored_device_id !== device_id) {
@@ -214,7 +310,7 @@ module.exports = function(RED) {
// Snapshot the Rust crypto store to disk so E2EE state survives
// restarts. No-op when E2EE is disabled.
async function persistCrypto() {
if(!cryptoSnapshotPath) {
if(!cryptoSnapshotPath || cryptoCleared || !cryptoReady) {
return;
}
try {
@@ -227,7 +323,10 @@ module.exports = function(RED) {
// Discard all persisted crypto state for this account. Used when the
// device ID changes - the old crypto store belongs to a device that
// no longer exists and the Rust crypto stack refuses to load it.
// Resolves to false if the in-memory database could not be deleted
// (e.g. it is still held open), true otherwise.
async function discardCryptoStore() {
let complete = true;
// remove the persisted Rust crypto snapshot
try {
if(cryptoSnapshotPath) {
@@ -253,18 +352,84 @@ module.exports = function(RED) {
let dbs = await indexedDB.databases();
for(let db of dbs) {
if(db.name && db.name.indexOf(cryptoDbPrefix) === 0) {
await new Promise(function(resolve) {
// Wait for the delete to actually finish. While
// a connection is open the request only fires
// "blocked" and completes once it closes, so
// treating "blocked" as done would leave the
// database in place.
let deleted = await new Promise(function(resolve) {
let req = indexedDB.deleteDatabase(db.name);
req.onsuccess = req.onerror = req.onblocked = function(){ resolve(); };
let timer = setTimeout(function(){ resolve(false); }, 10000);
req.onsuccess = function(){ clearTimeout(timer); resolve(true); };
req.onerror = function(){ clearTimeout(timer); resolve(false); };
});
if(!deleted) {
complete = false;
node.warn("Could not delete in-memory crypto database " + db.name + " (still in use)");
}
}
}
}
} catch(e) {
complete = false;
node.warn("Could not clear in-memory crypto database: " + e);
}
return complete;
}
// "Encryption hold": after the encryption data is cleared the node
// must not reconnect with the same device ID. The homeserver still
// has that device's old one-time keys, so the regenerated keys are
// rejected ("One time key ... already exists") and incoming
// encrypted messages can never be decrypted. A marker file records
// the cleared device; while it matches, the node stays disconnected
// (across deploys and restarts) until the bot logs in as a new
// session, which gets a new device ID.
let encryptionHoldPath = localStorageDir + '/encryption-hold.json';
function readEncryptionHold() {
try {
if(fs.pathExistsSync(encryptionHoldPath)) {
return fs.readJsonSync(encryptionHoldPath);
}
} catch(e) {
node.warn("Could not read " + encryptionHoldPath + ": " + e);
return { clearedAt: null, deviceId: null }; // unreadable - stay on hold
}
return null;
}
node.getEncryptionHold = readEncryptionHold;
// Clear all encryption data for this account (used by the
// /matrix-chat/clear-encryption-data admin endpoint). The client is
// stopped first: the running crypto stack holds its IndexedDB
// database open, which blocks deleting it. Snapshotting is disabled
// so the node's close handler cannot write the store back to disk.
// The hold marker is written before anything is deleted, so the
// node stays disconnected even if this is interrupted.
node.clearEncryptionData = async function() {
cryptoCleared = true;
stopClient();
// also stops the crypto stack when the client never started
// syncing (stopClient() above skips that case)
haltClient(node.matrixClient);
if(clientStarting) {
// A startup in progress (crypto init, startClient) stops
// itself once it sees cryptoCleared. Wait for it, so its
// crypto stack has let go of the database before deleting.
await Promise.race([clientStarting, new Promise(function(r) { setTimeout(r, 15000); })]);
haltClient(node.matrixClient);
}
let deviceId = (node.matrixClient && node.matrixClient.getDeviceId())
|| node.deviceId || getStoredDeviceId(localStorage) || null;
fs.writeJsonSync(encryptionHoldPath, { clearedAt: new Date().toISOString(), deviceId: deviceId });
return {
complete: await discardCryptoStore(),
deviceId: deviceId,
};
};
function stopClient() {
if(node.matrixClient && node.matrixClient.clientRunning) {
node.matrixClient.stopClient();
@@ -280,9 +445,81 @@ module.exports = function(RED) {
}
}
// matrix-js-sdk issues its first /sync request after its startup
// prelude without checking whether the client was stopped in the
// meantime, and nothing handles that request's AbortError, which
// takes Node-RED down. Attach a no-op catch to every request the
// (stopped) SyncApi stores, including ones created later.
function swallowSyncRequests(syncApi) {
if(!syncApi || syncApi[SYNC_GUARD]) {
return;
}
syncApi[SYNC_GUARD] = true;
let current = syncApi.currentSyncRequest;
let guard = function(request) {
if(request && typeof request.catch === 'function') {
request.catch(function() {});
}
};
guard(current);
Object.defineProperty(syncApi, 'currentSyncRequest', {
configurable: true,
enumerable: true,
get: function() { return current; },
set: function(request) { current = request; guard(request); },
});
}
// Stop a client for good, also when startClient() is still running:
// the SDK can create its SyncApi after stopClient() was called.
function haltClient(client) {
if(!client) {
return;
}
let syncApi = client.syncApi;
swallowSyncRequests(syncApi);
client.stopClient();
if(syncApi) {
syncApi.stop();
}
}
// Resolves once the SDK has sent its first /sync request (or the
// client is not starting up), so stopping it cannot race the sync
// loop's startup prelude. Bounded to 5 seconds.
function syncPreludeDone(client) {
let deadline = Date.now() + 5000;
return new Promise(function(resolve) {
(function check() {
let syncApi = client && client.syncApi;
if(!client || !client.clientRunning || !syncApi || syncApi.currentSyncRequest
|| client.getSyncState() !== null || Date.now() > deadline) {
return resolve();
}
setTimeout(check, 50);
})();
});
}
node.on('close', function(done) {
stopClient();
persistCrypto().finally(function() {
closing = true;
// Let an in-progress startup (crypto init, startClient) settle
// first, so the client is stopped in a known state (bounded,
// well inside Node-RED's close timeout).
let starting = clientStarting
? Promise.race([clientStarting.catch(function(){}), new Promise(function(r) { setTimeout(r, 5000); })])
: Promise.resolve();
starting.then(function() {
return syncPreludeDone(node.matrixClient);
}).then(function() {
// guard the SyncApi before stopClient() drops it
swallowSyncRequests(node.matrixClient && node.matrixClient.syncApi);
stopClient();
// a startup that is still running past the wait above is
// halted by run() once startClient() returns
haltClient(node.matrixClient);
return persistCrypto();
}).finally(function() {
if(node.globalAccess) {
try {
node.context().global.set('matrixClient["'+node.userId+'"]', undefined);
@@ -307,6 +544,9 @@ module.exports = function(RED) {
async function setupClient() {
const sdk = await sdkPromise;
if(closing) {
return;
}
const {
RelationType, RoomEvent, RoomMemberEvent, HttpApiEvent, ClientEvent,
MemoryStore, LocalStorageCryptoStore,
@@ -424,6 +664,9 @@ module.exports = function(RED) {
// Resolve the real homeserver via .well-known discovery so a
// delegating domain (e.g. "example.org") works as the server URL.
const baseUrl = await resolveHomeserverUrl(sdk, node.url);
if(closing) {
return;
}
if(baseUrl !== node.url) {
node.log(`Discovered homeserver ${baseUrl} for ${node.url} via .well-known`);
}
@@ -475,7 +718,36 @@ module.exports = function(RED) {
node.context().global.set('matrixClient["'+node.userId+'"]', node.matrixClient);
}
node.matrixClient.on(RoomEvent.Timeline, async function(event, room, toStartOfTimeline, removed, data) {
// Plain copy of an SDK User for msg.user, without its private
// (underscore) fields. The live User must not be modified: it
// is an EventEmitter, and deleting its "_events" key used to
// strip the listeners the SDK attached to it, so the client
// stopped receiving that user's presence/display name updates.
function snapshotUser(user) {
if(!user) {
return null;
}
let copy = {};
Object.keys(user).forEach(function(key) {
if(!/^_/.test(key)) {
copy[key] = user[key];
}
});
return copy;
}
// Wrap an async SDK event handler so a throw inside it is
// reported instead of becoming an unhandled promise rejection
// (which takes the whole Node-RED process down).
function guardAsync(what, handler) {
return function() {
handler.apply(this, arguments).catch(function(e) {
node.error("Error handling " + what + ": " + (e && e.stack || e));
});
};
}
node.matrixClient.on(RoomEvent.Timeline, guardAsync("timeline event", async function(event, room, toStartOfTimeline, removed, data) {
if (toStartOfTimeline) {
node.log("Ignoring" + (event.isEncrypted() ? ' encrypted' : '') +" timeline event [" + (event.getContent()['msgtype'] || event.getType()) + "]: (" + room.name + ") " + event.getId() + " for reason: paginated result");
return; // ignore paginated results
@@ -521,52 +793,77 @@ module.exports = function(RED) {
isThread : event.getContent()?.['m.relates_to']?.rel_type === RelationType.Thread,
mentions : event.getContent()["m.mentions"] || null,
userId : event.getSender(),
user : node.matrixClient.getUser(event.getSender()),
user : snapshotUser(node.matrixClient.getUser(event.getSender())),
topic : event.getRoomId(),
eventId : event.getId(),
event : event,
};
// remove keys from user property that start with an underscore
Object.keys(msg.user).forEach(function (key) {
if (/^_/.test(key)) {
delete msg.user[key];
}
});
node.log(`Received ${msg.encrypted ? 'encrypted ' : ''}timeline event [${msg.type}]: (${room.name}) ${event.getSender()} :: ${msg.content.body} ${toStartOfTimeline ? ' [PAGINATED]' : ''}`);
node.emit("Room.timeline", event, room, toStartOfTimeline, removed, data, msg);
});
}));
// Resolve a room that may not be in the store yet (invites are
// reported before the SDK stores the room). Gives up after 5s.
function waitForRoom(roomId) {
let room = node.matrixClient.getRoom(roomId);
if(room) {
return Promise.resolve(room);
}
return new Promise(function(resolve) {
let timer = setTimeout(function() {
node.matrixClient.off(ClientEvent.Room, onRoom);
resolve(node.matrixClient.getRoom(roomId));
}, 5000);
function onRoom(r) {
if(r && r.roomId === roomId) {
clearTimeout(timer);
node.matrixClient.off(ClientEvent.Room, onRoom);
resolve(r);
}
}
node.matrixClient.on(ClientEvent.Room, onRoom);
});
}
// handle auto-joining rooms
node.matrixClient.on(RoomMemberEvent.Membership, async function(event, member) {
if(node.initializedAt > event.getDate()) {
return; // skip events that occurred before our client initialized
node.matrixClient.on(RoomMemberEvent.Membership, guardAsync("room membership event", async function(event, member) {
if (member.membership !== "invite" || String(member.userId).toLowerCase() !== String(node.userId).toLowerCase()) {
return;
}
if (member.membership === "invite" && member.userId === node.userId) {
node.log("Got invite to join room " + member.roomId);
if(node.autoAcceptRoomInvites) {
node.matrixClient.joinRoom(member.roomId).then(function() {
node.log("Automatically accepted invitation to join room " + member.roomId);
}).catch(function(e) {
node.warn("Cannot join room (could be from being kicked/banned) " + member.roomId + ": " + e);
});
}
let room = node.matrixClient.getRoom(event.getRoomId());
node.emit("Room.invite", {
type : 'm.room.member',
userId : event.getSender(),
topic : event.getRoomId(),
topicName : (room ? room.name : null) || null,
event : event,
eventId : event.getId(),
// Invites reach us as stripped state with no timestamp
// (getDate() is null; the old `initializedAt > null` check
// skipped every invite, #141). Those are always handled,
// including invites still pending from while Node-RED was
// offline. Dated member events from before startup are
// skipped: initial sync replays the bot's past invites in
// the timeline of rooms it has already joined.
if(event.getDate() && event.getDate() < node.initializedAt) {
return;
}
node.log("Got invite to join room " + member.roomId);
if(node.autoAcceptRoomInvites) {
node.matrixClient.joinRoom(member.roomId).then(function() {
node.log("Automatically accepted invitation to join room " + member.roomId);
}).catch(function(e) {
node.warn("Cannot join room (could be from being kicked/banned) " + member.roomId + ": " + e);
});
}
});
node.matrixClient.on(ClientEvent.Sync, async function(state, prevState, data) {
// The SDK fires this before it stores the invited room,
// so wait for the room to get its name.
let room = await waitForRoom(member.roomId);
node.emit("Room.invite", {
type : 'm.room.member',
userId : event.getSender(),
topic : event.getRoomId(),
topicName : (room ? room.name : null) || null,
event : event,
eventId : event.getId(),
});
}));
node.matrixClient.on(ClientEvent.Sync, guardAsync("sync state change", async function(state, prevState, data) {
node.debug("SYNC [STATE=" + state + "] [PREVSTATE=" + prevState + "]");
if(prevState === null && state === "PREPARED" ) {
// Occurs when the initial sync is completed first time.
@@ -632,10 +929,10 @@ module.exports = function(RED) {
node.error("Connection to Matrix server lost");
});
}
});
}));
node.matrixClient.on(HttpApiEvent.SessionLoggedOut, async function(errorObj){
node.matrixClient.on(HttpApiEvent.SessionLoggedOut, guardAsync("logout", async function(errorObj){
// Example if user auth token incorrect:
// {
// errcode: 'M_UNKNOWN_TOKEN',
@@ -649,7 +946,7 @@ module.exports = function(RED) {
node.error("Authentication failure: " + errorObj);
stopClient();
});
}));
// incoming device-verification requests from other users/devices
node.matrixClient.on(CryptoEvent.VerificationRequestReceived, function(request) {
@@ -664,6 +961,25 @@ module.exports = function(RED) {
async function run() {
try {
if(node.e2ee){
// Encryption data was cleared: only connect once the
// bot has logged in as a new session (new device ID).
let hold = readEncryptionHold();
if(hold) {
let deviceId = node.matrixClient.getDeviceId();
// a hold without a device ID (unreadable file, or the
// device was unknown when clearing) cannot tell the
// old session from a new one, so it always holds
if(!deviceId || !hold.deviceId || deviceId === hold.deviceId) {
node.warn(
`Encryption data was cleared for session ${hold.deviceId || '(unknown)'}, so the Matrix client stays disconnected. ` +
'Log in as a new session ("Update Access Token" in the server configuration), then deploy. ' +
`To reconnect with the same session anyway, delete ${encryptionHoldPath} and redeploy.`
);
return;
}
fs.removeSync(encryptionHoldPath);
node.log(`New session ${deviceId} after encryption data was cleared; connecting with a fresh encryption store.`);
}
node.log("Initializing crypto...");
ensureIndexedDBShim();
// If the device ID has changed (e.g. a new login), the
@@ -678,10 +994,26 @@ module.exports = function(RED) {
} else {
await restoreCryptoStore(cryptoSnapshotPath);
}
await node.matrixClient.initRustCrypto({
useIndexedDB: true,
cryptoDatabasePrefix: cryptoDbPrefix,
});
try {
await node.matrixClient.initRustCrypto({
useIndexedDB: true,
cryptoDatabasePrefix: cryptoDbPrefix,
});
} catch(cryptoInitError) {
// Most likely a corrupted encryption store (e.g. from
// an incomplete migration). Fail with instructions
// rather than a bare WASM error, and never clear the
// data automatically - the user decides via the UI.
throw new Error(
`Encryption initialization failed (${cryptoInitError && cryptoInitError.message || cryptoInitError}). ` +
'This may indicate a corrupted encryption store. ' +
'To recover, log in as a new session ("Update Access Token" in the server configuration) and deploy, ' +
'which starts a fresh encryption store. Use "Clear encryption data" there first to also delete the old data. ' +
'Previously received encrypted messages will no longer be decryptable.',
{ cause: cryptoInitError }
);
}
cryptoReady = true;
let crypto = node.matrixClient.getCrypto();
if(crypto) {
// Blacklist (refuse to encrypt to) unverified devices only
@@ -692,10 +1024,25 @@ module.exports = function(RED) {
// periodically persist crypto state so it survives an unclean shutdown
cryptoSnapshotInterval = setInterval(persistCrypto, 5 * 60 * 1000);
}
if(closing || cryptoCleared) {
// closed (or encryption data cleared) while crypto
// was initializing
if(cryptoSnapshotInterval) {
clearInterval(cryptoSnapshotInterval);
cryptoSnapshotInterval = null;
}
haltClient(node.matrixClient);
return;
}
node.log("Connecting to Matrix server...");
await node.matrixClient.startClient({
initialSyncLimit: node.initialSyncLimit
});
if(closing || cryptoCleared) {
// closed (or encryption data cleared) while
// startClient() was running
haltClient(node.matrixClient);
}
} catch(error) {
node.error(error);
}
@@ -704,7 +1051,7 @@ module.exports = function(RED) {
// do an authed request and only continue if we don't get an error
// this prevent the matrix client from crashing Node-RED on invalid auth token
(function checkAuthTokenThenStart() {
if(node.matrixClient.clientRunning) {
if(closing || node.matrixClient.clientRunning) {
return;
}
@@ -717,7 +1064,10 @@ module.exports = function(RED) {
node.matrixClient.whoami()
.then(
function(data) {
if((typeof data['device_id'] === undefined || !data['device_id']) && !node.deviceId && !getStoredDeviceId(localStorage)) {
if(closing) {
return;
}
if(!data['device_id'] && !node.deviceId && !getStoredDeviceId(localStorage)) {
node.error("/whoami request did not return device_id. You will need to manually set one in your configuration because this cannot be automatically fetched.");
}
if('device_id' in data && data['device_id'] && !node.deviceId) {
@@ -731,14 +1081,23 @@ module.exports = function(RED) {
node.error(`User ID provided is ${node.userId} but token belongs to ${data['user_id']}`);
return;
}
run().catch((error) => node.error(error));
clientStarting = run().catch((error) => node.error(error));
},
function(err) {
// if the error isn't authentication related retry in a little bit
if(err.code !== "M_UNKNOWN_TOKEN") {
retryStartTimeout = setTimeout(checkAuthTokenThenStart, 15000);
node.error("Auth check failed: " + err);
if(closing) {
return;
}
// An invalid or logged-out token will never work, so
// report it and stop. (This used to check err.code,
// which the SDK never sets - it is err.errcode - so
// a bad token was retried every 15s forever.)
if(err && err.errcode === "M_UNKNOWN_TOKEN") {
node.error("Matrix connection failed: the access token is invalid or has been logged out (M_UNKNOWN_TOKEN). Log in again to get a new access token.");
return;
}
// anything else (network, server down) - retry in a little bit
retryStartTimeout = setTimeout(checkAuthTokenThenStart, 15000);
node.error("Auth check failed: " + err);
}
)
})();
@@ -949,6 +1308,63 @@ module.exports = function(RED) {
}
});
/**
* Clear encryption data for a server configuration, used when the crypto
* store is corrupted and needs to be reset. Same flows.write protection
* as the other admin endpoints, so it is not publicly exposed.
*
* Actions (on req.body.id, the server config node):
* - status : whether the node is on an encryption hold (see
* readEncryptionHold in MatrixServerNode)
* - clear : (default) stop the client, delete the encryption data and
* put the node on hold until it logs in as a new session.
* Requires confirmDelete: true to prevent accidental data loss.
*/
RED.httpAdmin.post(
"/matrix-chat/clear-encryption-data",
RED.auth.needsPermission('flows.write'),
async function(req, res) {
try {
const serverNode = RED.nodes.getNode(req.body.id);
if(!serverNode || typeof serverNode.clearEncryptionData !== 'function') {
return res.json({ result: 'error', message: 'Server configuration not found or not running. Save and deploy the server configuration node first.' });
}
const action = req.body.action || 'clear';
if(action === 'status') {
return res.json({ result: 'ok', hold: serverNode.getEncryptionHold() });
}
if(action !== 'clear') {
return res.json({ result: 'error', message: 'Unknown action: ' + action });
}
if(!serverNode.e2ee) {
// the hold is only checked with E2EE on, and there is no
// encryption data to clear without it
return res.json({ result: 'error', message: 'End-to-end encryption is not enabled for this server configuration, so there is no encryption data to clear.' });
}
if(req.body.confirmDelete !== true) {
return res.json({ result: 'error', message: 'Confirmation required. Pass confirmDelete: true to proceed.' });
}
const { complete, deviceId } = await serverNode.clearEncryptionData();
if(!complete) {
return res.json({
result: 'error',
message: 'The Matrix client was stopped but some encryption data is still in use and could not be removed. Restart Node-RED to finish clearing it.'
});
}
serverNode.log(`Encryption data cleared for session ${deviceId}. The client stays disconnected until it logs in as a new session.`);
return res.json({
result: 'ok',
deviceId: deviceId,
message: 'Encryption data has been cleared. The Matrix client is disconnected and will stay disconnected, even after deploys and restarts, until the bot logs in as a new session.',
});
} catch(error) {
res.json({ result: 'error', message: String(error && error.message || error) });
}
});
/**
* Lists and drives device verification requests for the config editor's
* "Verification" button (the verification list modal). Same flows.write
+10 -5
View File
@@ -27,28 +27,33 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
node.warn("No matrix server selected");
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
}
if(!msg.userId) {
if(!msg.userId || typeof msg.userId !== 'string') {
node.error("msg.userId must be set to edit/create a user (ex: @user:server.com)", msg);
msg.error = "msg.userId must be set to edit/create a user (ex: @user:server.com)";
node.send([null, msg]);
return;
}
@@ -66,7 +71,7 @@ module.exports = function(RED) {
msg.payload = e;
node.send([msg, null]);
}).catch(function(e){
node.warn("Error creating/editing user " + e);
node.error("Error creating/editing user " + e, msg);
msg.error = e;
node.send([null, msg]);
});
+5 -5
View File
@@ -60,13 +60,13 @@
<dt>msg.userId
<span class="property-type">string</span>
</dt>
<dd> ID of user to create/edit (ex: @bob:example.com)</dd>
<dd> ID of user to deactivate (ex: @bob:example.com)</dd>
<dt class="optional">msg.erase
<span class="property-type">string</span>
<span class="property-type">bool</span>
</dt>
<dd>
The following additional actions are performed during deactivation if set to true (defaults to false)
The following additional actions are performed during deactivation if set to <code>true</code> (or the string <code>"true"</code>; defaults to false)
<ul>
<li>Remove the user's display name</li>
<li>Remove the user's avatar URL</li>
@@ -79,8 +79,8 @@
<ol class="node-ports">
<li>Success
<dl class="message-properties">
<dt>msg.error <span class="property-type">object</span></dt>
<dd>empty object response</dd>
<dt>msg.payload <span class="property-type">object</span></dt>
<dd>the response from Synapse (contains <code>id_server_unbind_result</code>)</dd>
</dl>
</li>
<li>Error
+13 -7
View File
@@ -27,28 +27,33 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
node.warn("No matrix server selected");
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
}
if(!msg.userId) {
node.error("msg.userId must be set to edit/create a user (ex: @user:server.com)", msg);
if(!msg.userId || typeof msg.userId !== 'string') {
node.error("msg.userId must be set to deactivate a user (ex: @user:server.com)", msg);
msg.error = "msg.userId must be set to deactivate a user (ex: @user:server.com)";
node.send([null, msg]);
return;
}
@@ -61,13 +66,14 @@ module.exports = function(RED) {
'POST',
path,
undefined,
{"erase": (msg.erase || false)},
// Synapse requires a JSON boolean (a string is rejected with 400)
{"erase": (msg.erase === true || msg.erase === 'true')},
{"prefix": '' })
.then(function(e){
msg.payload = e;
node.send([msg, null]);
}).catch(function(e){
node.warn("Error deactivating user " + e);
node.error("Error deactivating user " + e, msg);
msg.error = e;
node.send([null, msg]);
});
+12 -4
View File
@@ -12,6 +12,7 @@ module.exports = function(RED) {
node.error('Server must be configured on the node.', {});
return;
}
node.server.register(node);
this.encodeUri = function(pathTemplate, variables) {
for (const key in variables) {
if (!variables.hasOwnProperty(key)) {
@@ -26,21 +27,24 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
node.warn("No matrix server selected");
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -48,12 +52,16 @@ module.exports = function(RED) {
msg.topic = node.roomId || msg.topic;
if(!msg.topic) {
msg.error = "room must be defined in either msg.topic or in node config";
node.error("room must be defined in either msg.topic or in node config", msg);
node.send([null, msg]);
return;
}
if(!msg.userId) {
msg.error = "msg.userId is required to set user into a room";
node.error("msg.userId is required to set user into a room", msg);
node.send([null, msg]);
return;
}
@@ -72,7 +80,7 @@ module.exports = function(RED) {
msg.topic = e.room_id;
node.send([msg, null]);
}).catch(function(e){
node.warn("Error joining user to room " + e);
node.error("Error joining user to room " + e, msg);
msg.error = e;
node.send([null, msg]);
});
+11 -9
View File
@@ -8,7 +8,7 @@
outputs:2,
credentials: {
server: { type:"text", required: true },
sharedSecret: { type:"text", required: true },
sharedSecret: { type:"password", required: true },
},
defaults: {
name: { value: null },
@@ -36,7 +36,7 @@
<div class="form-row">
<label for="node-input-sharedSecret"><i class="fa fa-user"></i> Registration Shared Secret</label>
<input type="text" id="node-input-sharedSecret">
<input type="password" id="node-input-sharedSecret">
</div>
<div class="form-tips" style="margin-bottom: 12px;">
Public registration does not need to be enabled to register. Using your <code>registration_shared_secret</code> from within your <code>homeserver.yaml</code> server config file will allow Node-RED to register users.
@@ -61,7 +61,7 @@
<dd> Set the displayname for the user (default to username if not set). </dd>
<dt>msg.payload.username
<span class="property-type">object</span>
<span class="property-type">string</span>
</dt>
<dd> Username for the new user. </dd>
@@ -70,7 +70,7 @@
</dt>
<dd> Password for the new user. </dd>
<dt>msg.payload.admin
<dt class="optional">msg.payload.admin
<span class="property-type">bool</span>
</dt>
<dd> If true, the new user will be an admin. Default to false. </dd>
@@ -87,15 +87,17 @@
<h3>Outputs</h3>
<ol class="node-ports">
<li>Success
<dl class="message-properties">`
<dt>msg.eventId <span class="property-type">string</span></dt>
<dd>the eventId from the posted message.</dd>
<dl class="message-properties">
<dt>msg.payload <span class="property-type">object</span></dt>
<dd>the registration response from Synapse: <code>user_id</code>, <code>access_token</code>, <code>device_id</code> and <code>home_server</code>.</dd>
</dl>
</li>
<li>Error
<dl class="message-properties">
<dt>msg.error <span class="property-type">string</span></dt>
<dd>the error that occurred.</dd>
<dt>msg.error <span class="property-type">string | object</span></dt>
<dd>the error that occurred. <code>msg.payload.password</code> is removed.</dd>
<dt class="optional">msg.error_extra <span class="property-type">string</span></dt>
<dd>which step failed (fetching the nonce or submitting the registration).</dd>
</dl>
</li>
</ol>
+90 -64
View File
@@ -1,5 +1,4 @@
module.exports = function(RED) {
const utf8 = require('utf8');
const crypto = require('crypto');
function MatrixSynapseRegister(n) {
@@ -24,87 +23,114 @@ module.exports = function(RED) {
node.on("input", async function (msg) {
const got = (await import('got')).default;
if(!msg.payload.username) {
node.error("msg.payload.username is required", msg);
const fail = function(text, error, extra) {
// before node.error(): Catch nodes get a copy of msg as it is now
if(msg.payload && typeof msg.payload === 'object') {
delete msg.payload.password;
}
// only the message: got's errors carry the request options,
// which include the password
msg.error = error ? String(error.message || error) : text;
if(extra) {
msg.error_extra = extra;
}
node.error(text, msg);
node.status({fill:"red",shape:"ring",text:"Failure"});
node.send([null, msg]);
};
if(!msg.payload || typeof msg.payload !== 'object') {
fail("msg.payload must be an object with username and password");
return;
}
if(!msg.payload.password) {
node.error("msg.payload.password is required", msg);
if(!msg.payload.username || typeof msg.payload.username !== 'string') {
fail("msg.payload.username is required");
return;
}
await (async () => {
try {
var response = await got.get(this.server + '/_synapse/admin/v1/register', {
responseType: 'json'
});
} catch (error) {
msg.error = error;
msg.error_extra = 'Failed fetching nonce key from registration endpoint';
delete msg.payload.password;
node.status({fill:"red",shape:"ring",text:"Failure"});
node.send([null, msg]);
return;
}
if(!msg.payload.password || typeof msg.payload.password !== 'string') {
fail("msg.payload.password is required");
return;
}
var nonce = response.body.nonce;
if(!nonce) {
node.error('Could not get nonce from /_synapse/admin/v1/register', msg);
return;
}
if(msg.payload.user_type && typeof msg.payload.user_type !== 'string') {
fail("msg.payload.user_type must be a string");
return;
}
let hmac = crypto.createHmac("sha1", node.sharedSecret )
.update(utf8.encode(nonce))
.update("\x00")
.update(utf8.encode(msg.payload.username))
.update("\x00")
.update(utf8.encode(msg.payload.password))
.update("\x00")
.update(msg.payload.admin ? "admin" : "notadmin")
// avoid "//_synapse/..." (Synapse answers 404) when the URL ends in "/"
const registerUrl = String(node.server).replace(/\/+$/, '') + '/_synapse/admin/v1/register';
if(msg.payload.user_type || null) {
hmac.update("\x00")
.update(msg.payload.user_type);
}
let response;
try {
response = await got.get(registerUrl, {
responseType: 'json'
});
} catch (error) {
fail("Failed fetching nonce key from registration endpoint: " + error, error, 'Failed fetching nonce key from registration endpoint');
return;
}
hmac = hmac.digest('hex');
let nonce = response.body && response.body.nonce;
if(!nonce) {
fail('Could not get nonce from /_synapse/admin/v1/register');
return;
}
try {
response = await got.post(this.server + '/_synapse/admin/v1/register', {
json: {
"nonce": nonce,
"username": msg.payload.username,
"password": msg.payload.password,
"mac": hmac,
"admin": msg.payload.admin || false,
"user_type": msg.payload.user_type || null,
},
responseType: 'json'
});
} catch (error) {
msg.error = error;
msg.error_extra = 'Failed submitting registration request';
delete msg.payload.password;
node.status({fill:"red",shape:"ring",text:"Failure"});
node.send([null, msg]);
return;
}
// Strings are hashed as UTF-8 (crypto's default for strings). They
// used to be run through utf8.encode() first, which encoded every
// non-ASCII character twice, so Synapse rejected the MAC
// ("HMAC incorrect") for any non-ASCII username or password.
let hmac = crypto.createHmac("sha1", node.sharedSecret)
.update(nonce)
.update("\x00")
.update(msg.payload.username)
.update("\x00")
.update(msg.payload.password)
.update("\x00")
.update(msg.payload.admin ? "admin" : "notadmin");
node.status({fill:"green",shape:"dot",text:"Registered: " + msg.payload.username});
msg.payload = response.body;
node.send(msg);
})();
});
if(msg.payload.user_type) {
hmac.update("\x00")
.update(msg.payload.user_type);
}
node.on("close", function() {
node.server.deregister(node);
hmac = hmac.digest('hex');
let body = {
"nonce": nonce,
"username": msg.payload.username,
"password": msg.payload.password,
"mac": hmac,
"admin": msg.payload.admin || false,
"user_type": msg.payload.user_type || null,
};
if(msg.payload.displayname) {
// not part of the MAC
body.displayname = String(msg.payload.displayname);
}
try {
response = await got.post(registerUrl, {
json: body,
responseType: 'json'
});
} catch (error) {
let detail = error && error.response && error.response.body && error.response.body.error;
fail("Failed submitting registration request: " + (detail || error), error, 'Failed submitting registration request');
return;
}
node.status({fill:"green",shape:"dot",text:"Registered: " + msg.payload.username});
msg.payload = response.body;
node.send([msg, null]);
});
}
RED.nodes.registerType("matrix-synapse-register", MatrixSynapseRegister, {
credentials: {
server: { type:"text", value: null, required: true },
sharedSecret: { type:"text", value: null },
sharedSecret: { type:"password", value: null },
}
});
}
+12 -6
View File
@@ -16,21 +16,24 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
node.warn("No matrix server selected");
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -41,8 +44,11 @@ module.exports = function(RED) {
'limit': msg.limit || 100
};
if(msg.guests) {
queryParams['guests'] = msg.guests ? 'true' : 'false';
// msg.guests=false must be sent explicitly: Synapse defaults to
// including guests, so only sending the parameter when truthy
// made "false" impossible.
if(msg.guests !== undefined && msg.guests !== null) {
queryParams['guests'] = (msg.guests === true || msg.guests === 'true') ? 'true' : 'false';
}
if(msg.order_by) {
@@ -60,7 +66,7 @@ module.exports = function(RED) {
msg.payload = e;
node.send([msg, null]);
}).catch(function(e){
node.warn("Error fetching server user list " + e);
node.error("Error fetching server user list " + e, msg);
msg.error = e;
node.send([null, msg]);
});
+14 -3
View File
@@ -22,22 +22,24 @@ module.exports = function(RED) {
}
node.server.register(node);
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on('input', async function(msg) {
if (! node.server || ! node.server.matrixClient) {
msg.error = "No matrix server selected";
node.error("No matrix server selected", msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
@@ -68,14 +70,23 @@ module.exports = function(RED) {
if(!roomId) {
node.error('No room provided in msg.topic', msg);
msg.error = 'No room provided in msg.topic';
node.send([null, msg]);
return;
}
// The SDK treats any truthy value as "typing", so the string
// "false" (e.g. from a msg property) used to start typing.
if (typeof typing === 'string') {
typing = typing.trim().toLowerCase() === 'true';
}
typing = !!typing;
await node.server.matrixClient.sendTyping(roomId, typing, timeoutMs);
node.send([msg, null]);
} catch(e) {
node.error("Failed to send typing event " + msg.topic + ": " + e, msg);
msg.payload = e;
msg.error = e;
node.send([null, msg]);
}
});
+9 -12
View File
@@ -14,7 +14,7 @@
fileNameType: { value: "msg" },
fileNameValue: { value: "filename" },
contentType: { value: null },
generateThumbnails: { type: "checkbox", value: true },
generateThumbnails: { value: true },
},
label: function() {
return this.name || "Upload File";
@@ -82,12 +82,12 @@
style="width: auto; margin-left: 125px; vertical-align: top"
/>
<label for="node-input-generateThumbnails" style="width: auto;max-width:50%;">
Generate m.video thumbnails using ffmpeg
Generate thumbnails for images and videos
</label>
</div>
<div class="form-tips">
ffmpeg & ffprobe must be installed for thumbnail generation, calculating duration of video or audio file, and getting width & height for videos. This functionality is disabled otherwise.
Image thumbnails are always generated as PNG. ffmpeg & ffprobe must be installed for video thumbnails, calculating duration of video or audio file, and getting width & height for videos. This functionality is disabled otherwise.
</div>
<script type="text/javascript">
@@ -112,7 +112,7 @@
<dt>msg.payload
<span class="property-type">string | Buffer</span>
</dt>
<dd> A path to the file (string) or a file buffer (Buffer) to upload. If a buffer is provided, you must specify the filename for accurate type detection.</dd>
<dd> A path to the file (string) or a file buffer (Buffer) to upload. Relative paths are resolved against the <code>fileWorkingDirectory</code> setting if it is set. If a buffer is provided, you must specify the filename (and ideally <code>msg.contentType</code>) for accurate type detection.</dd>
<dt>msg.filename
<span class="property-type">string</span>
@@ -122,22 +122,22 @@
<dt>msg.body
<span class="property-type">string | null</span>
</dt>
<dd> The display name for the file when rendered in the chat. If left empty, the default display name is "Attachment".</dd>
<dd> The display name for the file when rendered in the chat. If left empty, the file name is used.</dd>
<dt class="optional">msg.contentType
<span class="property-type">string | null</span>
</dt>
<dd> Optional MIME Type of the file. If not provided, the type will be auto-detected based on the filename or buffer. If the detection fails, it will default to "text/plain".</dd>
<dd> Optional MIME Type of the file. If not provided, the type will be auto-detected from the filename. If the detection fails, it will default to "text/plain". The content type also decides the message type (<code>m.image</code>, <code>m.video</code>, <code>m.audio</code> or <code>m.file</code>) unless <code>msg.msgtype</code> is set.</dd>
<dt class="optional">msg.encrypted
<span class="property-type">boolean</span>
</dt>
<dd> Set to true if the file should be uploaded with encryption. The node handles encryption automatically if this is enabled.</dd>
<dd> Set to true if the file should be uploaded with encryption (required for encrypted rooms). The node handles encryption automatically if this is enabled. Encrypted files are uploaded as <code>application/octet-stream</code> without a filename, so the homeserver cannot see the real name or type.</dd>
<dt class="optional">msg.generateThumbnails
<span class="property-type">boolean</span>
</dt>
<dd> Set to true to generate thumbnails for image or video uploads. Thumbnails are generated automatically for supported types.</dd>
<dd> Overrides the node's "Generate thumbnails" setting for this message: <code>true</code> generates a thumbnail for image or video uploads, <code>false</code> skips it.</dd>
</dl>
<h3>Outputs</h3>
@@ -145,10 +145,7 @@
<li>Success
<dl class="message-properties">
<dt>msg.payload <span class="property-type">object</span></dt>
<dd>An object containing details of the uploaded file, including the URL (mxc URI), the MIME type, size, and any generated thumbnail information.</dd>
<dt>msg.eventId <span class="property-type">string</span></dt>
<dd>The eventId of the uploaded file message.</dd>
<dd>The message content for the uploaded file (<code>msgtype</code>, <code>body</code>, <code>filename</code>, <code>url</code> or <code>file</code> for encrypted uploads, and <code>info</code> with the MIME type, size, dimensions, duration and any thumbnail). Pass it to a Send Message node to post the file to a room. This node does not send a message itself.</dd>
</dl>
</li>
<li>Error
+109 -67
View File
@@ -29,11 +29,11 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
@@ -44,9 +44,8 @@ module.exports = function(RED) {
try {
if(file) {
let type = Mime.getType(file);
let ext = Mime.getExtension(file);
if(type) {
return {ext: ext, mime: type};
return {ext: Mime.getExtension(type), mime: type};
}
}
} catch (error) {
@@ -66,8 +65,8 @@ module.exports = function(RED) {
}
return fs.readFileSync(data);
} catch (error) {
node.error(`Error reading file buffer: ${error.message}`, msg);
throw error;
// the caller reports this (with msg), so Catch nodes fire once
throw new Error(`Error reading file buffer: ${error.message}`);
}
}
@@ -88,8 +87,7 @@ module.exports = function(RED) {
value = Number(property);
}
} catch (error) {
node.error(`Error evaluating value for type ${type}: ${error.message}`);
throw new Error("Invalid value evaluation");
throw new Error(`Invalid value evaluation for type ${type}: ${error.message}`);
}
return value;
}
@@ -98,7 +96,9 @@ module.exports = function(RED) {
async function onInput(msg) {
try {
if (!node.server || !node.server.matrixClient) {
node.warn("No matrix server selected");
node.error("No matrix server selected", msg);
msg.error = "No matrix server selected";
node.send([null, msg]);
return;
}
@@ -116,6 +116,14 @@ module.exports = function(RED) {
node.send([null, msg]);
return;
}
// Resolve a relative path once, so the size, dimension and
// ffprobe steps read the same file as the upload does.
if (typeof bufferOrPath === 'string' && RED.settings.fileWorkingDirectory && !path.isAbsolute(bufferOrPath)) {
bufferOrPath = path.resolve(RED.settings.fileWorkingDirectory, bufferOrPath);
}
let generateThumbnails = (typeof msg.generateThumbnails === 'boolean')
? msg.generateThumbnails
: node.generateThumbnails;
let filename = getToValue(msg, node.fileNameType, node.fileNameValue);
if (!filename || typeof filename !== 'string') {
@@ -139,6 +147,11 @@ module.exports = function(RED) {
node.warn("Content-type failed to detect, falling back to text/plain", msg);
contentType = 'text/plain';
}
// The final content type (msg.contentType / node setting /
// filename) decides the msgtype, so e.g. a buffer named
// "snapshot" with contentType image/png is still sent as m.image.
const Mime = (await import('mime')).default;
detectedFileType = { mime: contentType, ext: Mime.getExtension(contentType) || detectedFileType?.ext || 'bin' };
if (!msgtype) {
msgtype = autoDetectMatrixMessageType(detectedFileType);
}
@@ -153,12 +166,7 @@ module.exports = function(RED) {
try {
file = await node.server.matrixClient.uploadContent(
encryptedFile?.data || getFileBuffer(bufferOrPath, msg),
{
name: filename, // Name to give the file on the server.
rawResponse: false, // Return the raw body, rather than parsing the JSON.
type: contentType, // Content-type for the upload. Defaults to file.type, or applicaton/octet-stream.
onlyContentUri: false // Just return the content URI, rather than the whole body. Defaults to false. Ignored if opts.rawResponse is true.
});
uploadOptions(filename, contentType, !!encryptedFile));
} catch (e) {
node.error("Upload content error " + e, msg);
msg.error = e;
@@ -166,6 +174,15 @@ module.exports = function(RED) {
return;
}
// Encrypted media is opaque to the homeserver: upload it as
// application/octet-stream without a filename (like Element),
// the real name and type only live in the encrypted event.
function uploadOptions(name, type, encrypted) {
return encrypted
? { includeFilename: false, type: "application/octet-stream" }
: { name: name, type: type };
}
// we call this method when we need a file and cannot use the buffer
// so if we get passed a buffer we write it to a tmp file and return that
// otherwise we just return the string because it's already a file
@@ -215,24 +232,27 @@ module.exports = function(RED) {
}
}
async function addThumbnail(buffer) {
// Add a thumbnail to msg.payload.info. `thumbnailBuffer` is the
// plaintext thumbnail (used for dimension detection); `encrypted`
// is the {data, info} blob from encryptAttachment when the upload
// is encrypted, or null otherwise. We always size from the
// plaintext (imageSize/statSync can't read ciphertext) and upload
// the encrypted bytes when encrypting. AES-CTR preserves length,
// so the plaintext size matches the uploaded size.
async function addThumbnail(thumbnailBuffer, encrypted) {
try {
let thumbSize = imageSize(Buffer.isBuffer(buffer) ? buffer : buffer.data);
let thumbSize = imageSize(thumbnailBuffer);
msg.payload.info.thumbnail_info = {
w: thumbSize.width,
h: thumbSize.height,
size: getFileSize(Buffer.isBuffer(buffer) ? buffer : buffer.data)
mimetype: "image/png", // thumbnails are always rendered as PNG
size: getFileSize(thumbnailBuffer)
}
let uploadedThumbnail = await node.server.matrixClient.uploadContent(
Buffer.isBuffer(buffer) ? buffer : buffer.data,
{
name: "thumbnail.png", // Name to give the file on the server.
rawResponse: false, // Return the raw body, rather than parsing the JSON.
type: "image/png", // Content-type for the upload. Defaults to file.type, or applicaton/octet-stream.
onlyContentUri: false // Just return the content URI, rather than the whole body. Defaults to false. Ignored if opts.rawResponse is true.
});
// delete local file
if (msg.encrypted) {
encrypted ? encrypted.data : thumbnailBuffer,
uploadOptions("thumbnail.png", "image/png", !!encrypted));
if (encrypted) {
msg.payload.info.thumbnail_file = encrypted.info;
msg.payload.info.thumbnail_file.url = uploadedThumbnail.content_uri;
} else {
msg.payload.info.thumbnail_url = uploadedThumbnail.content_uri;
@@ -244,48 +264,64 @@ module.exports = function(RED) {
async function createImageThumbnail(bufferOrPath) {
try {
if (Buffer.isBuffer(bufferOrPath)) {
return sharp(bufferOrPath).resize({width: 320}).toBuffer();
}
return sharp(fs.readFileSync(bufferOrPath)).resize({width: 320}).toBuffer();
// always PNG (it is uploaded as image/png), never upscaled
let input = Buffer.isBuffer(bufferOrPath) ? bufferOrPath : fs.readFileSync(bufferOrPath);
return sharp(input).resize({width: 320, withoutEnlargement: true}).png().toBuffer();
} catch (error) {
node.error(`Error creating image thumbnail: ${error.message}`);
node.error(`Error creating image thumbnail: ${error.message}`, msg);
throw error;
}
}
function _ffmpegVideoThumbnail(filepath) {
return new Promise((resolve, reject) => {
let filename = `${msg._msgid}-screenshot.png`;
// a private temp dir per upload: a shared name (it used
// to be /tmp/<_msgid>-screenshot.png) collides when the
// same msg is fanned out to two upload nodes
let dir = tmp.dirSync({unsafeCleanup: true});
let filename = 'screenshot.png';
let cleanup = function() {
try { dir.removeCallback(); } catch (e) { /* already gone */ }
};
ffmpeg(filepath)
.on('end', async function () {
let path = `/tmp/${filename}`;
let buffer = getFileBuffer(path, msg);
let encryptedThumbnail = null;
if (msg.encrypted) {
encryptedThumbnail = await encryptAttachment(buffer);
msg.payload.info.thumbnail_file = encryptedFile.info;
}
try {
await addThumbnail(encryptedThumbnail || buffer);
fs.rmSync(path); // delete temporary thumbnail file
let buffer = getFileBuffer(path.join(dir.name, filename), msg);
let encryptedThumbnail = msg.encrypted
? await encryptAttachment(buffer)
: null;
await addThumbnail(buffer, encryptedThumbnail);
resolve();
} catch (e) {
return reject(new Error("Thumbnail upload failure: " + e));
reject(new Error("Thumbnail upload failure: " + e));
} finally {
cleanup();
}
})
.on('error', function (err) {
return reject(err);
cleanup();
reject(err);
})
.screenshots({
timestamps: [0],
filename: filename,
folder: '/tmp',
folder: dir.name,
size: '320x?'
});
});
}
// ffprobe reports stream duration as "N/A" for some containers
// (WebM/MKV); fall back to the container duration. The spec
// wants integer milliseconds.
function durationMs(stream, metadata) {
let seconds = parseFloat(stream && stream.duration);
if (!Number.isFinite(seconds)) {
seconds = parseFloat(metadata && metadata.format && metadata.format.duration);
}
return (Number.isFinite(seconds) && seconds > 0) ? Math.round(seconds * 1000) : undefined;
}
msg.payload = {};
if (msg.encrypted) {
msg.payload.file = encryptedFile?.info || {};
@@ -310,14 +346,12 @@ module.exports = function(RED) {
msg.payload.info.w = dimensions.width;
// Generate thumbnail for image
if (node.generateThumbnails) {
if (generateThumbnails) {
let thumbnailBuffer = await createImageThumbnail(bufferOrPath);
let encryptedThumbnail = null;
if (msg.encrypted) {
encryptedThumbnail = await encryptAttachment(thumbnailBuffer);
msg.payload.info.thumbnail_file = encryptedThumbnail.info;
}
await addThumbnail(encryptedThumbnail || thumbnailBuffer);
let encryptedThumbnail = msg.encrypted
? await encryptAttachment(thumbnailBuffer)
: null;
await addThumbnail(thumbnailBuffer, encryptedThumbnail);
}
} catch (e) {
node.error("thumbnail error: " + e, msg);
@@ -330,8 +364,9 @@ module.exports = function(RED) {
let audioStream = metadata?.streams.filter(function (stream) {
return stream.codec_type === "audio" || false;
})[0];
if (audioStream?.duration) {
msg.payload.info.duration = audioStream?.duration * 1000;
let duration = durationMs(audioStream, metadata);
if (duration) {
msg.payload.info.duration = duration;
}
} catch (e) {
node.error(e, msg);
@@ -347,7 +382,10 @@ module.exports = function(RED) {
return stream.codec_type === "video" || false;
})[0];
if (videoStream) {
msg.payload.info.duration = videoStream.duration * 1000;
let duration = durationMs(videoStream, metadata);
if (duration) {
msg.payload.info.duration = duration;
}
msg.payload.info.w = videoStream.width;
msg.payload.info.h = videoStream.height;
}
@@ -355,7 +393,7 @@ module.exports = function(RED) {
node.error("ffprobe error: " + e, msg);
}
if (node.generateThumbnails) {
if (generateThumbnails) {
try {
await _ffmpegVideoThumbnail(filepath);
} catch (e) {
@@ -365,10 +403,12 @@ module.exports = function(RED) {
deleteTempFile();
}
node.send(msg, null);
node.send([msg, null]);
} catch (error) {
node.error(`Unhandled error: ${error.message}`, msg);
node.log(error, msg);
msg.error = error.message;
node.send([null, msg]);
}
}
@@ -482,16 +522,18 @@ module.exports = function(RED) {
* @return {string} The base64 without padding.
*/
function encodeBase64(uint8Array) {
// Misinterpt the Uint8Array as Latin-1.
// window.btoa expects a unicode string with codepoints in the range 0-255.
// var latin1String = String.fromCharCode.apply(null, uint8Array);
// Use the builtin base64 encoder.
var paddedBase64 = btoa(uint8Array);
// Calculate the unpadded length.
var inputLength = uint8Array.length;
var outputLength = 4 * Math.floor((inputLength + 2) / 3) + (inputLength + 2) % 3 - 2;
// Return the unpadded base64.
return paddedBase64.slice(0, outputLength);
// Encode the actual bytes as unpadded base64.
//
// NOTE: do not pass the Uint8Array straight to btoa(). btoa() coerces
// its argument to a string, so btoa(uint8Array) base64-encodes the
// array's "1,2,3,..." text form rather than the raw bytes, producing a
// corrupt iv / sha256 and breaking attachment decryption on the
// recipient side ("unable to decrypt"). Buffer handles the byte view
// (offset/length) correctly even for pooled buffers.
return Buffer
.from(uint8Array.buffer, uint8Array.byteOffset, uint8Array.byteLength)
.toString('base64')
.replace(/=+$/, '');
}
/**
+1 -1
View File
@@ -54,7 +54,7 @@
</dl>
<dl class="message-properties">
<dt>msg.getter_errors <span class="property-type">undefined|object</span></dt>
<dd>Returned if there is an error thrown getting a user setting</dd>
<dd>Returned if getting a user setting failed. The key is the setting and the value is the error message.</dd>
</dl>
<dt class="optional">dynamic
<span class="property-type">string|object</span>
+23 -10
View File
@@ -17,11 +17,11 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
@@ -45,10 +45,11 @@ module.exports = function(RED) {
if(!Array.isArray(node.rules) || !node.rules.length) {
node.warn("No rules configured, skipping", msg);
return msg;
node.send([msg, null]);
return;
}
function getToValue(msg, rule) {
async function getToValue(msg, rule) {
var value = rule.to;
if (rule.tot === 'json') {
try {
@@ -74,12 +75,21 @@ module.exports = function(RED) {
} else if (rule.tot === 'date') {
value = Date.now();
} else if (rule.tot === 'jsonata') {
let expr;
try {
value = RED.util.evaluateJSONataExpression(rule.to,msg);
expr = RED.util.prepareJSONataExpression(rule.to, node);
} catch(e3) {
throw new Error("Invalid expression");
throw new Error("Invalid expression: " + e3.message);
}
return;
value = await new Promise(function(resolve, reject) {
RED.util.evaluateJSONataExpression(expr, msg, function(err, result) {
if (err) {
reject(new Error("Invalid expression: " + err.message));
} else {
resolve(result);
}
});
});
}
return value;
}
@@ -106,6 +116,7 @@ module.exports = function(RED) {
}
}
let cachedGetters = {};
for(let rule of node.rules) {
// [
// {
@@ -116,11 +127,10 @@ module.exports = function(RED) {
// }, ...
// ]
let cachedGetters = {};
if(rule.t === 'set') {
let value;
try {
value = getToValue(msg, rule);
value = await getToValue(msg, rule);
switch(rule.p) {
case "display_name":
await node.server.matrixClient.setDisplayName(value);
@@ -132,10 +142,13 @@ module.exports = function(RED) {
} catch(e) {
setterErrors[rule.p] = e.message;
}
// a later getter must not return what was cached before this set
cachedGetters = {};
} else if(rule.t === 'get') {
let value;
if(cachedGetters.hasOwnProperty(rule.p)) {
value = cachedGetters[rule.p];
setToValue(value, rule);
} else {
try {
// normalize some simpler events for easier access
@@ -150,7 +163,7 @@ module.exports = function(RED) {
setToValue(value, rule);
cachedGetters[rule.p] = value;
} catch(e) {
getterErrors[rule.p] = e;
getterErrors[rule.p] = (e && e.message) || String(e);
}
}
+2 -2
View File
@@ -16,10 +16,10 @@ module.exports = function(RED) {
}
node.server.register(node);
node.server.on("disconnected", function() {
node.server.listen(node, "disconnected", function() {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
+3 -10
View File
@@ -94,18 +94,11 @@ module.exports = function(RED) {
node.send(RED.util.cloneMessage(verificationMsg));
};
node.server.on("connected", onConnected);
node.server.on("disconnected", onDisconnected);
node.server.on("Verification.update", onVerificationUpdate);
if (node.server.isConnected && node.server.isConnected()) {
onConnected();
}
node.server.listen(node, "connected", onConnected);
node.server.listen(node, "disconnected", onDisconnected);
node.server.listen(node, "Verification.update", onVerificationUpdate);
node.on("close", function() {
node.server.removeListener("connected", onConnected);
node.server.removeListener("disconnected", onDisconnected);
node.server.removeListener("Verification.update", onVerificationUpdate);
node.server.deregister(node);
});
}
+12 -7
View File
@@ -28,28 +28,33 @@ module.exports = function(RED) {
node.status({ fill: "red", shape: "ring", text: "disconnected" });
node.server.on("disconnected", function(){
node.server.listen(node, "disconnected", function(){
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.server.on("connected", function() {
node.server.listen(node, "connected", function() {
node.status({ fill: "green", shape: "ring", text: "connected" });
});
node.on("input", function (msg) {
if (! node.server || ! node.server.matrixClient) {
node.warn("No matrix server selected");
msg.error = "No matrix server selected";
node.error(msg.error, msg);
node.send([null, msg]);
return;
}
if(!node.server.isConnected()) {
msg.error = "Matrix server connection is currently closed";
node.error("Matrix server connection is currently closed", msg);
node.send([null, msg]);
return;
}
if(!msg.userId) {
node.error("msg.userId must be set to get user whois data", msg);
if(!msg.userId || typeof msg.userId !== 'string') {
msg.error = "msg.userId must be set to get user whois data";
node.error(msg.error, msg);
node.send([null, msg]);
return;
}
@@ -62,13 +67,13 @@ module.exports = function(RED) {
{ $userId: msg.userId.toLowerCase() },
),
undefined,
msg.payload,
undefined, // GET requests cannot have a body
{ prefix: '' }
).then(function(e){
msg.payload = e;
node.send([msg, null]);
}).catch(function(e){
node.warn("Error fetching user whois information " + e);
node.error("Error fetching user whois information " + e, msg);
msg.error = e;
node.send([null, msg]);
});