-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
278 lines (263 loc) · 9.38 KB
/
index.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
const {
MatrixAppServiceBridge: {
Cli, AppServiceRegistration
},
Puppet,
MatrixPuppetBridgeBase,
utils: { download }
} = require("matrix-puppet-bridge");
const FacebookClient = require('./client');
const config = require('./config.json');
const path = require('path');
const puppet = new Puppet(path.join(__dirname, './config.json' ));
const debug = require('debug')('matrix-puppet:facebook');
const fs = require('fs');
class App extends MatrixPuppetBridgeBase {
getServicePrefix() {
return "facebook";
}
getServiceName () {
return "Facebook";
}
initThirdPartyClient() {
this.threadInfo = {};
this.thirdPartyClient = new FacebookClient();
this.thirdPartyClient.on('message', (data) => {
const { senderID, body, threadID, isGroup, attachments } = data;
const isMe = senderID === this.thirdPartyClient.userId;
debug("ISME? " + isMe);
this.threadInfo[threadID] = { isGroup };
var payload;
if (body) {
debug('Message has body');
payload = {
roomId: threadID,
// senderName: senderID,
senderId: isMe ? undefined : senderID,
text: body
};
debug(payload);
// Don't return yet -- there may be attachments, too.
this.handleThirdPartyRoomMessage(payload);
}
// We represent attachments as separate messages, as facebook does.
if (attachments.length >= 0) {
debug('Message has one or more attachments');
attachments.forEach(attachment => {
if (attachment.type === 'sticker') {
debug('Attachment is a sticker');
payload = {
roomId: threadID,
senderId: isMe? undefined : senderID,
text: attachment.description,
url: attachment.url,
h: 120,
w: 120,
mimetype: 'image/png'
};
this.handleThirdPartyRoomImageMessage(payload);
} else if (attachment.type === 'animated_image') {
debug('Attachment is an animated image');
payload = {
roomId: threadID,
senderId: isMe? undefined : senderID,
text: attachment.filename,
url: attachment.previewUrl,
w: attachment.previewWidth,
h: attachment.previewHeight,
mimetype: 'image/gif'
};
this.handleThirdPartyRoomImageMessage(payload);
} else if (attachment.type === 'photo') {
debug('Attachment is a photo');
payload = {
roomId: threadID,
senderId: isMe? undefined : senderID,
text: attachment.filename,
url: attachment.largePreviewUrl || attachment.previewUrl,
h: attachment.largePreviewHeight || attachment.previewHeight,
w: attachment.largePreviewWidth || attachment.previewWidth
};
this.handleThirdPartyRoomImageMessage(payload);
} else if (attachment.type === 'video') {
debug('Attachment is a video');
payload = {
roomId: threadID,
senderId: isMe? undefined : senderID,
text: attachment.filename,
url: attachment.url,
mimetype: 'video/mpeg'
};
this.handleThirdPartyRoomMessageWithAttachment(payload);
} else if (attachment.type === 'audio') {
debug('Attachment is an audio clip');
payload = {
roomId: threadID,
senderId: isMe? undefined : senderID,
text: attachment.filename,
url: attachment.url,
mimetype: 'audio/mpeg'
};
this.handleThirdPartyRoomMessageWithAttachment(payload);
} else if (attachment.type === 'file') {
debug('Attachment is a file');
payload = {
roomId: threadID,
senderId: isMe? undefined : senderID,
text: attachment.name + ': ' + attachment.url
};
this.handleThirdPartyRoomMessage(payload);
} else if (attachment.type === 'share' && 'facebookUrl' in attachment) {
debug('Attachment is a facebook share');
var url;
if (attachment.facebookUrl.startsWith('http://') || attachment.facebookUrl.startsWith('https://')) {
const urlObject = new URL(attachment.facebookUrl);
if (urlObject.hostname == "l.facebook.com" && urlObject.pathname == "/l.php") {
// Remove facebook link tracker
url = urlObject.searchParams.get("u");
} else {
url = attachment.facebookUrl;
}
} else {
url = 'https://www.facebook.com' + attachment.facebookUrl;
}
// Raw text message
let msgText = "";
if (attachment.title) {
msgText += attachment.title + ":\n";
}
if (attachment.description) {
msgText += attachment.description + "\n";
}
msgText += url;
if (attachment.source) {
msgText += "\n(" + attachment.source + ")";
}
// Formatted HTML message
let msgHtml = '<blockquote>';
if (attachment.title) {
msgHtml += `<strong><a href="${url}">${attachment.title}</a></strong><br/>`;
} else {
msgHtml += `<strong><a href="${url}">${url}</a></strong><br/>`;
}
if (attachment.description) {
msgHtml += `<em>${attachment.description}</em><br/>`;
}
if (attachment.source) {
msgHtml += `(${attachment.source})`;
}
msgHtml += '</blockquote>';
payload = {
roomId: threadID,
senderId: isMe? undefined : senderID,
text: msgText,
html: msgHtml
};
this.handleThirdPartyRoomMessage(payload);
} else {
debug('Unknown attachment type %s', attachment.type);
}
});
} else {
debug('Unknown message');
}
});
this.thirdPartyClient.on('friendsList', (friends) => {
let thirdPartyUsers = [];
for (const i in friends) {
const friend = friends[i];
thirdPartyUsers.push({
userId: friend.userID,
name: friend.fullName,
avatarUrl: friend.profilePicture
});
}
return this.joinThirdPartyUsersToStatusRoom(thirdPartyUsers);
});
return this.thirdPartyClient.login();
}
getThirdPartyUserDataById(id) {
return this.thirdPartyClient.getUserInfoById(id).then(userInfo=>{
debug('got user data', userInfo);
// TODO use userInfo.thumbSrc as the avatar
return { senderName: userInfo.name };
});
}
getThirdPartyRoomDataById(threadId) {
debug('getting third party room data by thread id', threadId);
let label = this.threadInfo[threadId].isGroup ? "Group" : "Friend";
return this.thirdPartyClient.getThreadInfo(threadId).then(data=>{
let roomData = {
name: data.name ? data.name : '',
topic: `Facebook ${label}`,
// Add Matrix's is_direct to support Facebook's isGroup
is_direct: !data.isGroup,
};
debug('room data', roomData);
return roomData;
});
}
sendMessageAsPuppetToThirdPartyRoomWithId(id, text) {
const url = text.match(/(https?:\/\/[^\s]+)/g);
if (url) {
return this.thirdPartyClient.sendMessage(id, {
body: text,
url: url[0],
});
} else {
return this.thirdPartyClient.sendMessage(id, text);
}
}
sendImageMessageAsPuppetToThirdPartyRoomWithId(id, data) {
return download.getTempfile( data.url, { tagFilename: true }).then(({path}) => {
let imgstream = fs.createReadStream(path);
return this.thirdPartyClient.sendMessage(id, {
body: data.text,
attachment: imgstream,
});
});
}
sendFileMessageAsPuppetToThirdPartyRoomWithId(id, data) {
return download.getTempfile( data.url, { tagFilename: true }).then(({path}) => {
let imgstream = fs.createReadStream(path);
return this.thirdPartyClient.sendMessage(id, {
body: data.text,
attachment: imgstream,
});
});
}
sendReadReceiptAsPuppetToThirdPartyRoomWithId(id) {
return this.thirdPartyClient.markAsRead(id);
}
}
new Cli({
port: config.port,
registrationPath: config.registrationPath,
generateRegistration: function(reg, callback) {
puppet.associate().then(()=>{
reg.setId(AppServiceRegistration.generateToken());
reg.setHomeserverToken(AppServiceRegistration.generateToken());
reg.setAppServiceToken(AppServiceRegistration.generateToken());
reg.setSenderLocalpart("facebookbot");
reg.addRegexPattern("users", "@facebook_.*", true);
reg.addRegexPattern("aliases", "#facebook_.*", true);
callback(reg);
}).catch(err=>{
console.error(err.message);
process.exit(-1);
});
},
run: function(port) {
const app = new App(config, puppet);
return puppet.startClient().then(()=>{
return app.initThirdPartyClient();
}).then(() => {
return app.bridge.run(port, config);
}).then(()=>{
console.log('Matrix-side listening on port %s', port);
}).catch(err=>{
console.error(err.message);
process.exit(-1);
});
}
}).run();