-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathbase.js
283 lines (274 loc) · 11.4 KB
/
base.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
const debug = require('./debug')('Base');
const Promise = require('bluebird');
const { Bridge, RemoteUser } = require('matrix-appservice-bridge');
const bangCommand = require('./bang-command');
class Base {
initThirdPartyClient() {
throw new Error("override me");
}
getThirdPartyUserDataById(_thirdPartyUserId) {
throw new Error("override me and return or resolve a promise with at least {senderName: 'some name'}, otherwise provide it in the original payload and i will never be invoked");
}
/**
* Async call to get additional data about the third party room
*
* @param {string} thirdPartyRoomId The unique identifier on the third party's side
* @returns {Promise->object} Promise resolving object { name:string, topic:string }
*/
getThirdPartyRoomDataById(_thirdPartyRoomId) {
throw new Error("override me");
}
/**
* The short string to put before the ghost user name.
* e.g. return "groupme" for @groupme_bob:your.host.com
*
* @returns {string} The string to prefix localpart user ids of ghost users
*/
getServicePrefix() {
throw new Error("override me");
}
/**
* Return a user id to match against 3rd party user id's in order to know if the message is of self-origin
*
* @returns {string} Your user ID from the perspective of the third party
*/
getPuppetThirdPartyUserId() {
throw new Error('override me');
}
sendMessageAsPuppetToThirdPartyRoomWithId(_thirdPartyRoomId, _messageText) {
throw new Error('override me');
}
constructor(config, puppet, bridge) {
const { info } = debug();
this.allowNullSenderName = false;
this.config = config;
this.puppet = puppet;
this.domain = config.bridge.domain;
this.deduplicationTag = this.config.deduplicationTag || this.defaultDeduplicationTag();
this.deduplicationTagPattern = this.config.deduplicationTagPattern || this.defaultDeduplicationTagPattern();
this.deduplicationTagRegex = new RegExp(this.deduplicationTagPattern);
this.bridge = bridge || this.setupBridge(config);
info('initialized');
}
setupBridge(config) {
return new Bridge(Object.assign({}, config.bridge, {
controller: {
onUserQuery: function(queriedUser) {
console.log('got user query', queriedUser);
return {}; // auto provision users w no additional data
},
onEvent: this.handleMatrixEvent.bind(this),
onAliasQuery: function() {
console.log('on alias query');
},
thirdPartyLookup: {
protocols: [this.getServicePrefix()],
getProtocol: function() {
console.log('get proto');
},
getLocation: function() {
console.log('get loc');
},
getUser: function() {
console.log('get user');
}
}
}
}));
}
getGhostUserFromThirdPartySenderId(id) {
return "@"+this.getServicePrefix()+"_"+id+":"+this.domain;
}
getRoomAliasFromThirdPartyRoomId(id) {
return "#"+this.getRoomAliasLocalPartFromThirdPartyRoomId(id)+':'+this.domain;
}
getThirdPartyUserIdFromMatrixGhostId(matrixGhostId) {
const patt = new RegExp(`^@${this.getServicePrefix()}_(.+)$`);
const localpart = matrixGhostId.replace(':'+this.domain, '');
const matches = localpart.match(patt);
return matches ? matches[1] : null;
}
getThirdPartyRoomIdFromMatrixRoomId(matrixRoomId) {
const { info } = debug(this.getThirdPartyRoomIdFromMatrixRoomId.name);
const patt = new RegExp(`^#${this.getServicePrefix()}_(.+)$`);
const room = this.puppet.getClient().getRoom(matrixRoomId);
info('reducing array of alases to a 3prid');
return room.getAliases().reduce((result, alias) => {
const localpart = alias.replace(':'+this.domain, '');
const matches = localpart.match(patt);
return matches ? matches[1] : result;
}, null);
}
getRoomAliasLocalPartFromThirdPartyRoomId(id) {
return this.getServicePrefix()+"_"+id;
}
getIntentFromThirdPartySenderId(senderId) {
return this.bridge.getIntent(this.getGhostUserFromThirdPartySenderId(senderId));
}
getIntentFromApplicationServerBot() {
return this.bridge.getIntent();
}
/**
* Returns a Promise resolving {senderName}
*
* Optional code path which is only called if the derived class does not
* provide a senderName when invoking handleThirdPartyRoomMessage
*
* @param {string} thirdPartyUserId
* @returns {Promise=>object}
*/
getOrInitRemoteUserStoreDataFromThirdPartyUserId(thirdPartyUserId) {
const { info } = debug(this.getOrInitRemoteUserStoreDataFromThirdPartyUserId.name);
const userStore = this.bridge.getUserStore();
return userStore.getRemoteUser(thirdPartyUserId).then(rUser=>{
if ( rUser ) {
info("found existing remote user in store", rUser);
return rUser;
} else {
info("did not find existing remote user in store, we must create it now");
return this.getThirdPartyUserDataById(thirdPartyUserId).then(thirdPartyUserData => {
info("got 3p user data:", thirdPartyUserData);
return new RemoteUser(thirdPartyUserId, {
senderName: thirdPartyUserData.senderName
});
}).then(rUser => {
return userStore.setRemoteUser(rUser);
}).then(()=>{
return userStore.getRemoteUser(thirdPartyUserId);
}).then(rUser => {
return rUser;
});
}
});
}
getOrCreateMatrixRoomFromThirdPartyRoomId(thirdPartyRoomId) {
const { warn, info } = debug(this.getOrCreateMatrixRoomFromThirdPartyRoomId.name);
const roomAlias = this.getRoomAliasFromThirdPartyRoomId(thirdPartyRoomId);
const roomAliasName = this.getRoomAliasLocalPartFromThirdPartyRoomId(thirdPartyRoomId);
info('looking up', thirdPartyRoomId);
const puppetClient = this.puppet.getClient();
return puppetClient.getRoomIdForAlias(roomAlias).then(({room_id}) => {
info("found matrix room via alias. room_id:", room_id);
return room_id;
}, (_err) => {
info("the room doesn't exist. we need to create it for the first time");
return Promise.resolve(this.getThirdPartyRoomDataById(thirdPartyRoomId)).then(thirdPartyRoomData => {
info("got 3p room data", thirdPartyRoomData);
const { name, topic } = thirdPartyRoomData;
info("creating room !!!!", ">>>>"+roomAliasName+"<<<<", name, topic);
return puppetClient.createRoom({
name, topic, room_alias_name: roomAliasName
}).then(({room_id}) => {
info("room created", room_id, roomAliasName);
return room_id;
});
});
}).then(matrixRoomId => {
info("making puppet join room", matrixRoomId);
return puppetClient.joinRoom(matrixRoomId).then(()=>{
info("returning room id after join room attempt", matrixRoomId);
return matrixRoomId
}, (err) => {
if ( err.message === 'No known servers' ) {
warn('we cannot use this room anymore because you cannot currently rejoin an empty room (synapse limitation? riot throws this error too). we need to de-alias it now so a new room gets created that we can actually use.');
return puppetClient.deleteAlias(roomAlias).then(()=>{
warn('deleted alias... trying again to get or create room.');
return this.getOrCreateMatrixRoomFromThirdPartyRoomId(thirdPartyRoomId)
})
} else {
warn("ignoring error from puppet join room: ", err.message);
return matrixRoomId;
}
});
});
}
/**
* Returns a promise
*/
handleThirdPartyRoomMessage(thirdPartyRoomMessageData, doNotTryToGetRemoteUserStoreData) {
const { info } = debug(this.handleThirdPartyRoomMessage.name);
info('handling third party room message', thirdPartyRoomMessageData);
const {
roomId,
senderName,
senderId,
text
} = thirdPartyRoomMessageData;
return this.getOrCreateMatrixRoomFromThirdPartyRoomId(roomId).then((roomId)=> {
info("got or created matrix room with id", roomId);
if ( senderId === undefined ) {
info("this message was sent by me, but did it come from a matrix client or a 3rd party client?");
info("if it came from a 3rd party client, we want to repeat it as a 'notice' message type");
info("if it came from a matrix client, then it's already in the client, sending again would dupe");
info("we use a tag on the end of messages to determine if it came from matrix");
if (this.isTaggedMatrixMessage(text)) {
info('it is from matrix, so just ignore it.');
} else {
info('it is from 3rd party client, so repeat it as a notice');
return Promise.mapSeries([
() => this.puppet.getClient().sendNotice(roomId, text)
], p => p());
}
} else {
if (!senderName && !this.allowNullSenderName) {
if ( doNotTryToGetRemoteUserStoreData ) throw new Error('preventing an endless loop');
info("no senderName provided with payload, will check store");
return this.getOrInitRemoteUserStoreDataFromThirdPartyUserId(senderId).then((remoteUser)=>{
info("got remote user from store, with a possible client API call in there somewhere", remoteUser);
const userData = { senderName: remoteUser.get('senderName') };
info("will retry now, once, after merging payload with remote user data", userData);
const newPayload = Object.assign({}, thirdPartyRoomMessageData, userData);
return this.handleThirdPartyRoomMessage(newPayload, true);
});
}
info("this message was not sent by me, send it the matrix room via ghost user as text");
const ghostIntent = this.getIntentFromThirdPartySenderId(senderId);
let promiseList = [];
promiseList.push(() => ghostIntent.join(roomId));
if (senderName)
promiseList.push(() => ghostIntent.setDisplayName(senderName));
promiseList.push(() => ghostIntent.sendText(roomId, text));
return Promise.mapSeries(promiseList, p => p());
}
});
}
handleMatrixEvent(req, _context) {
const { info, warn } = debug(this.handleMatrixEvent.name);
const data = req.getData();
if (data.type === 'm.room.message') {
info('incoming message. data:', data);
return this.handleMatrixMessageEvent(data);
} else {
return warn('ignored a matrix event', data.type);
}
}
handleMatrixMessageEvent(data) {
const { info } = debug(this.handleMatrixMessageEvent.name);
const { room_id, content: { body, msgtype } } = data;
if (msgtype === 'm.motice') {
info("ignoring message of type notice because the only messages of this type that");
info("should show up in this room are those that were sent by the bridge itself");
} else if (msgtype === 'm.text') {
if (this.handleMatrixUserBangCommand) {
const bc = bangCommand(body);
if (bc) return this.handleMatrixUserBangCommand(bc, data);
}
const thirdPartyRoomId = this.getThirdPartyRoomIdFromMatrixRoomId(room_id);
const msg = this.tagMatrixMessage(body);
return this.sendMessageAsPuppetToThirdPartyRoomWithId(thirdPartyRoomId, msg, data);
}
}
defaultDeduplicationTag() {
return " [m]";
}
defaultDeduplicationTagPattern() {
return " \\[m\\]";
}
tagMatrixMessage(text) {
return text+this.deduplicationTag;
}
isTaggedMatrixMessage(text) {
return this.deduplicationTagRegex.test(text);
}
}
module.exports = Base;