-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
258 lines (258 loc) · 9.39 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
"use strict";
const botbuilder = require('botbuilder');
const Bluebird = require('bluebird');
const WebSocket = require('ws');
const events = require('events');
const fetch = require('node-fetch');
const FormData = require('form-data');
const Package = require('./package');
class TypetalkBot extends botbuilder.DialogCollection {
constructor(options) {
super();
this.options = options;
this.localizer = options.localizer;
this.defaultDialogId = options.defaultDialogId || '/';
this.sessionStore = options.sessionStore || new botbuilder.MemoryStorage();
this.userStore = options.userStore || new botbuilder.MemoryStorage();
this.stream = new TypetalkStream(this.options);
this.profile = { name: null, info: null };
}
listen() {
this.stream.on('connected', () => {
this.emit('connected');
});
this.stream.on('message', (roomId, postId, account, message) => {
if (account.id === this.profile.info.account.id) {
return;
}
const storeId = `${roomId}:${account.id}`;
const userId = `${account.id}`;
const sessionOptions = {
dialogs: this,
dialogId: this.defaultDialogId,
localizer: this.localizer,
dialogArgs: {}
};
const session = new botbuilder.Session(sessionOptions);
session.on('send', (msg) => {
if (!msg)
return;
Bluebird.join(this.setSessionData(storeId, session.sessionState), this.setUserData(userId, session.userData)).then(() => {
this.stream.postMessage(roomId, msg.text, postId);
this.emit('send', msg);
});
});
session.on('error', (error) => {
this.emit('error', error, {
roomId: roomId,
postId: postId,
account: account,
text: message
});
});
session.on('quit', () => {
this.emit('quit', {
roomId: roomId,
postId: postId,
account: account,
text: message
});
});
Bluebird.join(this.getSessionData(storeId), this.getUserData(userId)).then((arg) => {
const sessionData = arg[0];
const userData = arg[1];
session.userData = userData || {};
session.userData.identity = account;
const typetalkMessage = {
roomId: roomId,
postId: postId,
account: account,
text: message,
from: { channelId: 'typetalk' }
};
session.dispatch(sessionData, typetalkMessage);
});
});
this.stream.getMyProfile()
.then((data) => {
this.profile['info'] = data;
this.profile['name'] = data.account.name;
this.stream.listen();
})
.catch((error) => {
console.error(error);
});
}
getUserData(userId) {
const options = { context: this.userStore };
return Bluebird.promisify(this.userStore.get, options)(userId)
.then((userdata) => userdata || {});
}
setUserData(userId, data) {
const options = { context: this.userStore };
return Bluebird.promisify(this.userStore.save, options)(userId, data)
.then(() => data);
}
getSessionData(storeId) {
const options = { context: this.sessionStore };
return Bluebird.promisify(this.sessionStore.get, options)(storeId)
.then((userdata) => userdata);
}
setSessionData(storeId, data) {
const options = { context: this.sessionStore };
return Bluebird.promisify(this.sessionStore.save, options)(storeId, data)
.then(() => data);
}
}
exports.TypetalkBot = TypetalkBot;
class TypetalkStream extends events.EventEmitter {
constructor(options) {
super();
this.host = 'typetalk.in';
this.connected = false;
if (!options.clientId || !options.clientSecret || !options.rooms) {
console.error('Not enough parameters provided. Please set client id, client secret and rooms');
process.exit(1);
}
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
this.rooms = options.rooms.split(',');
this.rooms.forEach((roomId) => {
if (!(roomId.length > 0 && parseInt(roomId) > 0)) {
console.error('Room id must be greater than 0');
process.exit(1);
}
});
}
connect() {
return new WebSocket(`https://${this.host}/api/v1/streaming`, {
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'User-Agent': `${Package.name} v${Package.version}`
}
});
}
listen() {
console.log('listen start');
let ws = this.ws = this.connect();
ws.on('open', () => {
this.connected = true;
console.log('Typetalk WebSocket connected');
this.emit('connected');
setInterval(() => ws.ping('ping'), 1000 * 60 * 10);
});
ws.on('message', (data, flags) => {
const event = JSON.parse(data);
if (event.type === 'postMessage') {
const topic = event.data.topic;
const post = event.data.post;
if (this.rooms.indexOf(topic.id + "") >= 0) {
this.emit('message', topic.id, post.id, post.account, post.message);
}
}
});
ws.on('error', (event) => {
console.error(`Typetalk WebSocket error: ${event}`);
if (!this.connected) {
setTimeout(() => this.listen(), 30000);
}
});
ws.on('pong', (data, flags) => console.error('pong'));
ws.on('close', (code, message) => {
this.connected = false;
console.error(`Typetalk WebSocket disconnected: code=${code}, message=${message}`);
console.error('Typetalk WebSocket try to reconnect');
setTimeout(() => this.listen(), 30000);
});
}
postMessage(topicId, message, replyTo) {
const form = new FormData();
form.append('message', message);
if (replyTo)
form.append('replyTo', replyTo);
return this.requestWithToken('POST', `/api/v1/topics/${topicId}`, null, null, form)
.catch((error) => {
console.error(error);
});
}
getMyProfile() {
return this.requestWithToken('GET', '/api/v1/profile');
}
updatetAccessToken() {
return new Promise((resolve, reject) => {
this.getAccessToken()
.then((data) => {
this.accessToken = data.access_token;
this.refreshToken = data.refresh_token;
resolve();
});
});
}
getAccessToken() {
const form = new FormData();
form.append('client_id', this.clientId);
form.append('client_secret', this.clientSecret);
form.append('grant_type', 'client_credentials');
form.append('scope', 'my,topic.read,topic.post');
return this.request('POST', '/oauth2/access_token', null, null, form);
}
requestWithToken(method, path, headers, query, body) {
headers = headers || {};
const req = () => {
headers['Authorization'] = `Bearer ${this.accessToken}`;
return this.request(method, path, headers, query, body)
.catch((error) => {
if (error.response.status === 401) {
return this.updatetAccessToken();
}
else {
throw error;
}
});
};
if (!this.accessToken) {
return this.updatetAccessToken().then(req);
}
else {
return req();
}
}
request(method, path, headers, query, body) {
headers = headers || {};
return this.fetching(method, path, headers, query, body)
.then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
}
else {
const error = new TypetalkError(response.statusText);
error.response = response;
throw error;
}
})
.then((response) => {
return response.json();
});
}
fetching(method, path, headers, query, body) {
headers['User-Agent'] = `${Package.name} v${Package.version}`;
const options = {
method: method,
headers: headers
};
if (method != 'GET') {
options.body = body;
}
const url = `https://${this.host}${path}${this.toQueryString(query)}`;
return fetch(url, options);
}
toQueryString(obj) {
const queryString = [];
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
queryString.push(`${prop}=${obj[prop]}`);
}
}
return queryString.length > 0 ? `?${queryString.join('&')}` : '';
}
}