-
-
Notifications
You must be signed in to change notification settings - Fork 625
Expand file tree
/
Copy pathsend.js
More file actions
78 lines (76 loc) · 2.09 KB
/
send.js
File metadata and controls
78 lines (76 loc) · 2.09 KB
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
import { request as _request } from 'node:https';
import { getLogger } from '@sitespeed.io/log';
const log = getLogger('sitespeedio.plugin.matrix');
function send(
host,
data,
message,
room,
accessToken,
retries = 3,
backoff = 5000,
transactionId = null
) {
if (transactionId === null) {
transactionId = `ssio-${Date.now()}`
}
const retryCodes = new Set([408, 429, 500, 503]);
return new Promise((resolve, reject) => {
const request = _request(
{
host,
port: 443,
path: `/_matrix/client/v3/rooms/${room}/send/m.room.message/${transactionId}`,
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(JSON.stringify(data), 'utf8')
},
method: 'PUT'
},
res => {
const { statusCode, statusMessage } = res;
if (statusCode < 200 || statusCode > 299) {
if (retries > 0 && retryCodes.has(statusCode)) {
setTimeout(() => {
return send(
host,
data,
message,
room,
accessToken,
retries - 1,
backoff * 2,
transactionId
);
}, backoff);
} else {
log.error(
`Got error from Matrix. Error Code: ${statusCode} Message: ${statusMessage}`
);
reject(new Error(`Status Code: ${statusCode}`));
}
} else {
const data = [];
res.on('data', chunk => {
data.push(chunk);
});
res.on('end', () => {
resolve(JSON.parse(Buffer.concat(data).toString()));
});
}
}
);
request.write(JSON.stringify(data));
request.end();
});
}
export default async function sendMatrix(host, room, accessToken, message) {
const data = {
msgtype: 'm.notice',
body: '',
format: 'org.matrix.custom.html',
formatted_body: message
};
return send(host, data, message, room, accessToken);
}