-
Notifications
You must be signed in to change notification settings - Fork 17
/
matrix.js
187 lines (175 loc) · 6.93 KB
/
matrix.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
let Adapter, localStorage, Robot, TextMessage, User;
try {
({Robot,Adapter,TextMessage,User} = require('hubot/es2015'));
} catch (e) {
try {
({Robot,Adapter,TextMessage,User} = require('hubot'));
} catch (error) {
let prequire = require('parent-require');
({Robot,Adapter,TextMessage,User} = prequire('hubot'));
}
}
let sdk = require('matrix-js-sdk');
let request = require('request');
let sizeOf = require('image-size');
if (localStorage == null) {
let {LocalStorage} = require('node-localstorage');
localStorage = new LocalStorage('./hubot-matrix.localStorage');
}
module.exports.use = (robot) => {
let that;
class Matrix extends Adapter {
constructor() {
super(...arguments);
this.robot.logger.info("Constructor");
}
handleUnknownDevices(err) {
let that = this;
return (() => {
let result = [];
for (var stranger in err.devices) {
var devices = err.devices[stranger];
result.push((() => {
let result1 = [];
for (let device in devices) {
let _ = devices[device];
that.robot.logger.info(`Acknowledging ${stranger}'s device ${device}`);
result1.push(that.client.setDeviceKnown(stranger, device));
}
return result1;
})());
}
return result;
})();
}
send(envelope, ...strings) {
return (() => {
let result = [];
for (var str of Array.from(strings)) {
that.robot.logger.info(`Sending to ${envelope.room}: ${str}`);
if (/^(f|ht)tps?:\/\//i.test(str)) {
result.push(that.sendURL(envelope, str));
} else {
result.push(that.client.sendNotice(envelope.room, str).catch(err => {
if (err.name === 'UnknownDeviceError') {
that.handleUnknownDevices(err);
return that.client.sendNotice(envelope.room, str);
}
}));
}
}
return result;
})();
}
emote(envelope, ...strings) {
return Array.from(strings).map((str) =>
that.client.sendEmoteMessage(envelope.room, str).catch(err => {
if (err.name === 'UnknownDeviceError') {
that.handleUnknownDevices(err);
return that.client.sendEmoteMessage(envelope.room, str);
}
}));
}
reply(envelope, ...strings) {
return Array.from(strings).map((str) =>
that.send(envelope, `${envelope.user.name}: ${str}`));
}
topic(envelope, ...strings) {
return Array.from(strings).map((str) =>
that.client.sendStateEvent(envelope.room, "m.room.topic", {
topic: str
}, ""));
}
sendURL(envelope, url) {
that.robot.logger.info(`Downloading ${url}`);
return request({url, encoding: null}, (error, response, body) => {
if (error) {
return that.robot.logger.info(`Request error: ${JSON.stringify(error)}`);
} else if (response.statusCode === 200) {
let info;
try {
let dims = sizeOf(body);
that.robot.logger.info(`Image has dimensions ${JSON.stringify(dims)}, size ${body.length}`);
if (dims.type === 'jpg') { dims.type = 'jpeg'; }
info = { mimetype: `image/${dims.type}`, h: dims.height, w: dims.width, size: body.length };
return that.client.uploadContent(body, {name: url, type: info.mimetype, rawResponse: false, onlyContentUri: true}).done(content_uri => {
return that.client.sendImageMessage(envelope.room, content_uri, info, url).catch(err => {
if (err.name === 'UnknownDeviceError') {
that.handleUnknownDevices(err);
return that.client.sendImageMessage(envelope.room, content_uri, info, url);
}
});
});
} catch (error1) {
error = error1;
that.robot.logger.info(error.message);
return that.send(envelope, ` ${url}`);
}
}
});
}
run() {
that.robot.logger.info(`Run ${that.robot.name}`);
let client = sdk.createClient(process.env.HUBOT_MATRIX_HOST_SERVER || 'https://matrix.org');
that.robot.matrixClient = client;
return client.login('m.login.password', {
user: process.env.HUBOT_MATRIX_USER || that.robot.name,
password: process.env.HUBOT_MATRIX_PASSWORD
}, (err, data) => {
if (err) {
that.robot.logger.error(err);
return;
}
that.user_id = data.user_id;
that.access_token = data.access_token;
that.device_id = data.device_id;
that.robot.logger.info(`Logged in ${that.user_id} on device ${that.device_id}`);
that.client = sdk.createClient({
baseUrl: process.env.HUBOT_MATRIX_HOST_SERVER || 'https://matrix.org',
accessToken: that.access_token,
userId: that.user_id,
deviceId: that.device_id,
sessionStore: new sdk.WebStorageSessionStore(localStorage)
});
that.client.on('sync', (state, prevState, data) => {
switch (state) {
case "PREPARED":
that.robot.logger.info(`Synced ${that.client.getRooms().length} rooms`);
// We really don't want to let people set the display name to something other than the bot
// name because the bot only reacts to it's own name.
const currentDisplayName = that.client.getUser(that.user_id).displayName;
if (that.robot.name !== currentDisplayName) {
that.robot.logger.info(`Setting display name to ${that.robot.name}`);
that.client.setDisplayName(that.robot.name, ()=>{});
}
return that.emit('connected');
}
});
that.client.on('Room.timeline', (event, room, toStartOfTimeline) => {
if ((event.getType() === 'm.room.message') && (toStartOfTimeline === false)) {
that.client.setPresence("online");
let message = event.getContent();
let name = event.getSender();
let user = that.robot.brain.userForId(name);
user.room = room.roomId;
if (name !== that.user_id) {
that.robot.logger.info(`Received message: ${JSON.stringify(message)} in room: ${user.room}, from: ${user.name} (${user.id}).`);
if (message.msgtype === "m.text") { that.receive(new TextMessage(user, message.body)); }
if ((message.msgtype !== "m.text") || (message.body.indexOf(that.robot.name) !== -1)) { return that.client.sendReadReceipt(event); }
}
}
});
that.client.on('RoomMember.membership', (event, member) => {
if ((member.membership === 'invite') && (member.userId === that.user_id)) {
return that.client.joinRoom(member.roomId).done(() => {
return that.robot.logger.info(`Auto-joined ${member.roomId}`);
});
}
});
return that.client.startClient(0);
});
}
}
that = new Matrix(robot);
return that;
};