-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.js
397 lines (388 loc) · 16.6 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
"use strict";
/*
* Created with @iobroker/create-adapter v2.1.1
*/
const axios = require("axios").default;
const fs = require("fs");
const helper = require("./lib/helper");
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require("@iobroker/adapter-core");
const matrix = require("matrix-js-sdk");
// the client for matrix communication
let matrixClient;
// local variable for fast access to static data
let fullUserId = "";
let roomId = "";
class MatrixOrg extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: "matrix-org",
});
this.on("ready", this.onReady.bind(this));
this.on("stateChange", this.onStateChange.bind(this));
this.on("message", this.onMessage.bind(this));
this.on("unload", this.onUnload.bind(this));
}
/**
* is called as part of the login chain to big for inline
* @param {*} data
*/
async matrixRoomIdResponse(data) {
if (data) {
await this.setStateAsync("matrixServerData.roomId", { val: data.room_id, ack: true });
roomId = data.room_id;
matrixClient.login("m.login.password", { "user": this.config.botName, "password": this.config.botPassword })
.then((data) => this.matrixLoginResponse(data))
.catch((err) => this.matrixLoginResponseErr(err));
}
}
/**
* is called as part of the login chain to big for inline
* @param {*} err
*/
async matrixRoomIdResponseErr(err) {
if (err) {
this.log.error("Server or room not found. Check port (443/8448), room name and server.");
this.log.error(JSON.stringify(err));
}
}
/**
* is called of last state of the login chain, Crypto disabled due to malfunction
* @param {*} data
*/
async matrixLoginResponse(data) {
if (data) {
fullUserId = data.user_id;
this.setState("info.connection", true, true);
try {
await matrixClient.startClient();
this.log.debug("client started!");
// init the receive callback
matrixClient.once("sync", (state, prevState, res) => {
this.log.debug("state: " + JSON.stringify(state));
this.log.debug("prevState: " + JSON.stringify(prevState));
this.log.debug("res: " + JSON.stringify(res));
try {
matrixClient.on("Room.timeline", (event, room, toStartOfTimeline) => this.onMatrixEvent(event, room, toStartOfTimeline));
} catch (err) {
this.log.error(err);
}
});
// autologin snippet by matrix-js-sdk
matrixClient.on("RoomMember.membership", (event, member) => {
if (this.config.autoJoin === true) {
if (member.membership === "invite" && member.userId === fullUserId) {
matrixClient.joinRoom(member.roomId).then(() => {
this.log.info("Auto-joined " + member.roomId);
});
}
}
});
} catch (err) {
this.log.error(err);
}
}
}
/**
* is called of last state of the login chain, Crypto disabled due to malfunction
* @param {*} err
*/
async matrixLoginResponseErr(err) {
if (err) {
this.log.error("Login has failed. Mostly credentials are wrong.");
this.log.error(err);
}
}
/**
* is called on every room event where the bot is in
* @param {*} event
* @param {*} room not used yet
* @param {*} toStartOfTimeline not used yet
*/
async onMatrixEvent(event, room, toStartOfTimeline) {
let messageUsed = false;
let reason = "";
if (event.event.type === "m.room.message") {
if (event.event.sender !== fullUserId) {
if (event.event.content.msgtype === "m.text") {
if (event.event.room_id === roomId) {
this.setStateAsync("receiveMessage", { val: event.event.content.body, ack: true });
messageUsed = true;
} else {
reason = "roomid don't fit: " + event.event.content.room_id + " is not the expected " + roomId;
this.log.debug("room:" + room + " toStartOfTimeline" + toStartOfTimeline);
}
} else {
reason = "message type is not m.text";
}
} else {
reason = "It was my own message.";
}
} else {
reason = "type not m.room.message";
}
if (messageUsed === false) {
this.log.debug("Message ignored due to: " + reason);
}
}
/**
* @param {string} message
*/
async sendMessageToMatrix(message) {
try {
const roomId = await this.getStateAsync("matrixServerData.roomId");
if (roomId) {
const state = "send message to room with access token!";
try {
const data = { "body": message, "msgtype": "m.text" };
matrixClient.sendEvent(roomId.val, "m.room.message", data);
} catch (err) {
this.log.error(err);
this.log.error("error during: " + state);
}
}
} catch (error) {
this.log.error(error);
this.log.error("error during: matrixServerData.roomId");
}
}
/***
* @param {object} message
*/
async sendHtmlToMatrix(message) {
const roomId = await this.getStateAsync("matrixServerData.roomId");
if (roomId) {
const state = "send message with html content to room with access token!";
try {
const data = { "body": message.text, msgtype: "m.text", format: "org.matrix.custom.html", formatted_body: message.html };
matrixClient.sendEvent(roomId.val, "m.room.message", data);
} catch (err) {
this.log.error(err);
this.log.error("error during: " + state);
}
}
}
/**
* send the file as an image to matrix
* @param {*} buffer contain the binary data from the image
* @param {string} fileType mime type of the image
*/
async sendFileToMatrix(buffer, fileType) {
try {
const uploadResponse = await matrixClient.uploadContent(buffer, { rawResponse: false, type: fileType });
const matrixUrl = uploadResponse.content_uri;
let msgtype = matrix.MsgType.File;
let info = {};
if (fileType.startsWith("image")) {
msgtype = matrix.MsgType.Image;
} else if (fileType.startsWith("video")) {
msgtype = matrix.MsgType.Video;
info = {
mimetype: fileType
};
}
const content = {
msgtype: msgtype,
url: matrixUrl,
info: info,
body: "",
};
await matrixClient.sendMessage(roomId, null, content, undefined);
} catch (err) {
this.log.error(err);
this.log.error("Sending of file failed");
}
}
/**
* send file from url or base64 encoded data to matrix as image
* @param {object} fileObject
*/
async sendFile(fileObject) {
this.log.debug(JSON.stringify(fileObject));
const file = String(fileObject.file);
const b64dataString = helper.getBufferAndNameFromBase64String(file);
const b64dataObject = helper.getBufferAndNameFromBase64Object(fileObject.file);
let fileType;
let buffer;
if (b64dataString) {
this.log.debug("String detected");
buffer = b64dataString.buffer;
fileType = b64dataString.mimeType;
} else if (b64dataObject) {
this.log.debug("Object detected");
buffer = b64dataObject.buffer;
fileType = b64dataObject.mimeType;
} else if (file.startsWith("https://") || file.startsWith("http://")) {
try {
const imageResponse = await axios.get(file, { responseType: "arraybuffer" });
fileType = imageResponse.headers["content-type"];
this.log.debug("http mimetype: " + fileType);
buffer = imageResponse.data;
} catch (err) {
this.log.error(err);
this.log.error("read from file failed.");
}
} else if (file.startsWith("file://")) {
if (fileObject.type) {
fileType = fileObject.type;
this.log.debug("file filetype: " + fileType);
}
try {
let fileName = file.slice(7);
if (helper.isWindows()) {
if (file.startsWith("file:///")) {
fileName = file.slice(8);
}
}
buffer = fs.readFileSync(fileName);
} catch (err) {
this.log.error(err);
}
} else {
this.log.error("no matching data found!");
}
try {
if (fileType === undefined) {
fileType = helper.getFileTypeFromData(buffer);
this.log.debug("guessed file type: " + fileType);
} else {
this.log.debug("file type: " + fileType);
}
} catch (error) {
this.log.error(error);
this.log.error("getFileType call failed");
}
try {
this.sendFileToMatrix(buffer, String(fileType));
} catch (err) {
this.log.error(err);
this.log.error("Send file failed!");
}
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
this.unloaded = false;
// Reset the connection indicator during startup
this.setState("info.connection", false, true);
// message will send after a change of the object sendMessage
this.subscribeStates("sendMessage");
if (this.config.serverIp === "") {
this.log.error("No server set!");
} else {
try {
let baseURL = "";
if (this.config.serverPort === "443") {
baseURL = "https://" + this.config.serverIp;
} else {
baseURL = "https://" + this.config.serverIp + ":" + this.config.serverPort;
}
matrixClient = matrix.createClient({ baseUrl: baseURL });
matrixClient.getRoomIdForAlias(this.config.roomName)
.then((data) => this.matrixRoomIdResponse(data))
.catch((err) => this.matrixRoomIdResponseErr(err));
} catch (err) {
this.log.error(err);
this.log.error("Server not reached! " + this.config.serverIp + ":" + this.config.serverPort + " with room: " + this.config.roomName);
this.setState("info.connection", false, true);
}
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
this.unloaded = true;
try {
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
if (state) {
// The state was changed
if (state.val) {
this.log.debug("try send");
if (state.ack === false) { // This is ioBroker convention, only send commands if ack = false
if (state.val === "image") {
this.sendFile({ file: { type: "image/png", base64: "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACmSURBVFhH7ZdhCoAgDEZnd9D737T8xJkNNY1Ef+yB2LTcC1qWOT20kCBgjIkh0WwfmeuIxyGYnRzIPElgFSqgAvsKOOdCzeZ1y7EcZzDG16HvwtckihLdA4xxk3HeGGttc17Cc+lN6Ds/dlO6w6/ItQHn7H4GcDK3Em/zNboE5KKjcQstQxVQARVYLlDdC2YzvBfMQgVUYB8BlMWfn2E1ZJ7Fv+dEF0UZoNhXp9NnAAAAAElFTkSuQmCC" } });
} else {
this.sendMessageToMatrix(state.val.toString());
}
}
}
} else {
// The state was deleted
this.log.info(`state ${id} deleted`);
}
}
/**
* Is called if a object is changed
* @param {*} obj
*/
onMessage(obj) {
if (typeof obj === "object") {
this.log.debug(JSON.stringify(obj));
// {"command":"send","message":{"file":"https://sciphy.de/toDownload/test.png"},"from":"system.adapter.javascript.0","_id":12345678}
// {"command":"send","message":"Hello!","from":"system.adapter.javascript.0","_id":12345678}
// {"command":"send","message":{"file":{"type":"image/png","base64":"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACmSURBVFhH7ZdhCoAgDEZnd9D737T8xJkNNY1Ef+yB2LTcC1qWOT20kCBgjIkh0WwfmeuIxyGYnRzIPElgFSqgAvsKOOdCzeZ1y7EcZzDG16HvwtckihLdA4xxk3HeGGttc17Cc+lN6Ds/dlO6w6/ItQHn7H4GcDK3Em/zNboE5KKjcQstQxVQARVYLlDdC2YzvBfMQgVUYB8BlMWfn2E1ZJ7Fv+dEF0UZoNhXp9NnAAAAAElFTkSuQmCC"}},"from":"system.adapter.javascript.0","_id":12345678}
if (obj.message) {
if (obj.command === "send") {
this.log.debug("send command arrived");
if (obj.message.file) {
this.log.debug("file command is triggered!");
this.sendFile(obj.message);
} else if (obj.message.html) {
this.log.debug("html message");
this.sendHtmlToMatrix(obj.message);
} else {
this.log.debug("send command is triggered!" + obj.message);
if (obj.message) {
this.log.debug("message send");
this.sendMessageToMatrix(obj.message);
}
if (obj.callback) {
this.log.debug("callback added");
this.sendTo(obj.from, obj.command, "Message computed", obj.callback);
}
}
}
}
}
}
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new MatrixOrg(options);
} else {
// otherwise start the instance directly
new MatrixOrg();
}
// testcode for JS scripts in ioBroker
// sendTo("matrix-org.0", "image test filesystem windows!");
// sendTo("matrix-org.0",{file: "file:///C:/tmp/images/test.png"});
// sendTo("matrix-org.0", "image test json!");
// sendTo("matrix-org.0",{file:{type:"image/png",base64:"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACmSURBVFhH7ZdhCoAgDEZnd9D737T8xJkNNY1Ef+yB2LTcC1qWOT20kCBgjIkh0WwfmeuIxyGYnRzIPElgFSqgAvsKOOdCzeZ1y7EcZzDG16HvwtckihLdA4xxk3HeGGttc17Cc+lN6Ds/dlO6w6/ItQHn7H4GcDK3Em/zNboE5KKjcQstQxVQARVYLlDdC2YzvBfMQgVUYB8BlMWfn2E1ZJ7Fv+dEF0UZoNhXp9NnAAAAAElFTkSuQmCC"}});
// sendTo("matrix-org.0", "image test data!");
// sendTo("matrix-org.0",{file:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACmSURBVFhH7ZdhCoAgDEZnd9D737T8xJkNNY1Ef+yB2LTcC1qWOT20kCBgjIkh0WwfmeuIxyGYnRzIPElgFSqgAvsKOOdCzeZ1y7EcZzDG16HvwtckihLdA4xxk3HeGGttc17Cc+lN6Ds/dlO6w6/ItQHn7H4GcDK3Em/zNboE5KKjcQstQxVQARVYLlDdC2YzvBfMQgVUYB8BlMWfn2E1ZJ7Fv+dEF0UZoNhXp9NnAAAAAElFTkSuQmCC"});
// sendTo("matrix-org.0", "Html!");
// sendTo("matrix-org.0",{html: "<h1>Hello World!</h1>", text: "Hello World!"});
// sendTo("matrix-org.0", "html table");
// sendTo("matrix-org.0",{html: "<table><tr><td>1</td><td>2</td></tr><tr><td>a</td><td>b</td></tr><table>", text: "Your client can not show html!"});
// sendTo("matrix-org.0", "test ready.");