-
Notifications
You must be signed in to change notification settings - Fork 1
/
TNAPI.js
470 lines (440 loc) · 17.5 KB
/
TNAPI.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
const path = require('path');
const fs = require('fs');
const https = require('https');
const Message = require('./message');
const MultiMediaMessage = require("./multi_media_message");
const MessageContainer = require("./message_container");
const mime = require("mime");
const { EventEmitter } = require('events');
const MESSAGE_TYPE = 0;
const MULTIMEDIA_MESSAGE_TYPE = 1;
const SENT_MESSAGE_TYPE = 2;
const RECEIVED_MESSAGE_TYPE = 1;
const SIP_ENDPOINT = "prod.tncp.textnow.com";
class Client extends EventEmitter {
static Message = Message;
static MultiMediaMessage = MultiMediaMessage;
static MessageContainer = MessageContainer;
/**
* Please run init after this. I needed async, I'm sorry.
*/
constructor(/*username, sid_cookie, csrf_cookie*/) {
/*await this.init(username, sid_cookie, csrf_cookie);*/
super();
this.delete_on_send = false;
}
async init(username, sid_cookie, csrf_cookie) {
this._user_cookies = {};
this._good_parse = false;
this._user_cookies_file = path.join(path.dirname(__dirname), 'user_cookies.json');
try {
this._user_cookies = JSON.parse(fs.readFileSync(this._user_cookies_file, 'utf-8'));
this._good_parse = true;
} catch {
fs.writeFileSync(this._user_cookies_file, "{}");
}
this.username = username;
this.allowed_events = ["message"];
this.events = [];
this.cookies = {};
if (this.username in Object.keys(this._user_cookies)) {
const sid = sid_cookie ? sid_cookie : this._user_cookies[this.username]['sid'];
const csrf = csrf_cookie ? csrf_cookie : this._user_cookies[this.username]['csrf'];
this.cookies = {
'connect.sid': sid,
'_csrf': csrf,
};
if (sid_cookie && csrf_cookie && !(this._good_parse)) {
fs.writeFileSync(this._user_cookies_file, JSON.stringify(this._user_cookies), "utf-8");
}
}
else {
const { sid, csrf } = (sid_cookie && csrf_cookie) ? ({ sid: sid_cookie, csrf: csrf_cookie }) : (console.error("Please provide an sid and csrf!") && process.exit());
this.cookies = {
'connect.sid': sid,
'_csrf': csrf,
};
this._user_cookies[this.username] = {
'sid': sid,
'csrf': csrf,
};
fs.writeFileSync(this._user_cookies_file, JSON.stringify(this._user_cookies));
}
this.headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36 ',
'x-csrf-token': await this.get_initial_csrf_token()
};
if (this.delete_on_send) {
let messages = await this.get_all_read_messages();
while ( messages.length > 0 ) {
for (let x = 0; x < messages.length; x++) {
await messages[x].delete();
}
messages = await this.get_all_read_messages();
}
}
setInterval(async () => {
const unread_msgs = await this.get_unread_messages();
for (let msg = 0; msg < unread_msgs.length; msg++) {
await unread_msgs[msg].mark_as_read();
console.log(unread_msgs[msg]);
this.emit("message", unread_msgs[msg]);
}
}, 1000);
}
/**
* @private
* @param {string} text
* @returns {string}
*/
_replace_newlines(text) {
return text.replace(/(?<!\\)\n/g, "\n");
}
/**
*
* @param {Object} _cookies
* @returns {string} Cookies primed for the cookie parameter
*/
processCookies(_cookies) {
if (!_cookies) return "";
let outputString = "";
let starter = true;
for (var x in Object.keys(_cookies)) {
if (!starter) {
outputString += ";";
}
else {
starter = false;
}
outputString += `${Object.keys(_cookies)[x]}=${_cookies[Object.keys(_cookies)[x]]}`;
}
return outputString;
}
reverseCookie(_set_cookie) {
if (!_set_cookie) return;
const kwookies = _set_cookie.map(elem => elem.split("; ")[0]);
for (let x = 0; x < kwookies.length; x++) {
let cookie = kwookies[x];
this.cookies[cookie.split("=")[0]] = cookie.split("=")[1];
}
return;
}
get_initial_csrf_token() {
const req = https.request('https://www.textnow.com/messaging', {
headers: {
cookie: this.processCookies(this.cookies)
}
});
const myPromise = new Promise((resolve, reject) => {
req.on("response", (response) => {
var body = "";
response.on("data", data => {
body += data;
});
response.on("end", () => {
if (response.statusCode == 200) {
this.reverseCookie(response.headers['set-cookie']);
resolve(/csrf-token" content="(?<csrf_token>.*?)"/.exec(body).groups.csrf_token);
}
else {
reject(`Non 200 response. (${response.statusCode})`);
}
});
})
});
req.end();
return myPromise;
}
auth_reset(sid_cookie, csrf_cookie) {
let user_cookies = JSON.parse(fs.readFileSync(this._user_cookies_file, "utf-8"));
if (this.username in Object.keys(user_cookies)) {
delete user_cookies[this.username];
fs.writeFileSync(this._user_cookies_file, JSON.stringify(user_cookies));
this.init(this.username, sid_cookie, csrf_cookie);
}
else {
if (sid_cookie && csrf_cookie) {
user_cookies[this.username] = {
"sid": sid_cookie,
"csrf": csrf_cookie
}
fs.writeFileSync(this._user_cookies_file, JSON.stringify(user_cookies))
}
else {
throw Error("You haven't authenticated before.");
}
}
}
delete(id) {
const myPromise = new Promise((resolve, reject) => {
const req = https.request(`https://www.textnow.com/api/users/${this.username}/messages/${id}`, {
headers: {
...this.headers,
cookie: this.processCookies(this.cookies)
},
method: "DELETE"
});
req.on("response", res => {
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
if (Math.floor(res.statusCode/100) == 2) {
this.reverseCookie(res.headers['set-cookie']);
resolve(body);
}
else {
reject(res.statusCode);
}
});
res.on("error", err => {
reject(err);
});
});
req.on("error", err => {
reject(err);
});
req.end();
});
return myPromise;
}
get_messages() {
const req = https.request("https://www.textnow.com/api/users/" + this.username + "/messages", {
headers: {
...this.headers,
cookie: this.processCookies(this.cookies)
}
});
const myPromise = new Promise((resolve, reject) => {
req.on("error", err => {
reject(err);
});
req.on("response", response => {
let body = "";
response.on("data", data => {
body += data;
});
response.on("end", () => {
this.reverseCookie(response.headers['set-cookie']);
if (Math.floor(response.statusCode / 100) == 2) {
const raw_messages = JSON.parse(body).messages;
let messages = raw_messages.map(msg => {
return !(msg["message"].startsWith("http")) ? new Message(msg, this) : new MultiMediaMessage(msg, this);
});
resolve(new MessageContainer(messages, this));
}
else {
reject("Non 200 response code.", response);
}
});
});
req.end();
});
return myPromise;
}
get_raw_messages() {
const req = https.request("https://www.textnow.com/api/users/" + this.username + "/messages", {
headers: {
...this.headers,
cookie: this.processCookies(this.cookies)
}
});
const myPromise = new Promise((resolve, reject) => {
req.on("error", err => {
reject(err);
});
req.on("response", response => {
let body = "";
response.on("data", data => {
body += data;
});
response.on("end", () => {
this.processCookies(response.headers['set-cookie']);
if (Math.floor(response.statusCode / 100) == 2) {
resolve(JSON.parse(body).messages);
}
else {
reject("Non 200 response code.", response);
}
});
});
req.end();
});
return myPromise;
}
async get_sent_messages() {
const messages = await this.get_messages();
const sent_messages = messages.filter(msg => msg.direction == SENT_MESSAGE_TYPE);
return new MessageContainer(sent_messages, this);
}
async get_received_messages() {
const messages = await this.get_messages();
const received_messages = messages.filter(msg => msg.direction == RECEIVED_MESSAGE_TYPE);
return new MessageContainer(received_messages, this);
}
async get_unread_messages() {
const messages = await this.get_received_messages();
const read_messages = messages.filter(msg => !msg.read);
return new MessageContainer(read_messages, this);
}
async get_read_messages() {
const messages = await this.get_received_messages();
const read_messages = messages.filter(msg => msg.read);
return new MessageContainer(read_messages, this);
}
async get_all_read_messages() {
const messages = await this.get_messages();
const read_messages = messages.filter(msg => msg.read);
return new MessageContainer(read_messages, this);
}
send_mms(to, file) {
const myPromise = new Promise((resolve, reject) => {
const mime_type = mime.getType(file);
const file_type = mime_type.split("/")[0];
const has_video = file_type == "video";
const msg_type = file_type == "image" ? 2 : 4;
const file_url_holder_req = https.request(`https://www.textnow.com/api/v3/attachment_url?message_type=${msg_type}`, {
headers: {
cookie: this.processCookies(this.cookies),
...this.headers
}
});
file_url_holder_req.on("response", res => {
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
if (Math.floor(res.statusCode / 100) == 2) {
const file_url_holder = JSON.parse(body)["result"];
const raw = fs.readFileSync(file);
const headers_place_file = {
'accept': '*/*',
'content-type': mime_type,
'accept-language': 'en-US,en;q=0.9',
'mode': 'cors',
'method': 'PUT',
'credentials': 'omit'
};
const place_file_req = https.request(file_url_holder, {
headers: {
cookie: this.processCookies(this.cookies),
...headers_place_file
},
method: "PUT"
});
place_file_req.on("response", pres => {
let pbody = "";
pres.on("data", pdata => {
pbody += pdata;
});
pres.on("end", () => {
if (Math.floor(pres.statusCode / 100) == 2) {
const json_data = {
"contact_value": to,
"contact_type": 2, "read": 1,
"message_direction": 2, "message_type": msg_type,
"from_name": this.username,
"has_video": has_video,
"new": true,
"date": new Date().toISOString(),
"attachment_url": file_url_holder,
"media_type": file_type
}
const send_file_req = https.request("https://www.textnow.com/api/v3/send_attachment", {
headers: {
cookie: this.processCookies(this.cookies),
...this.headers
},
method: "POST"
});
send_file_req.on("response", sres => {
let sbody = "";
sres.on("data", sdata => {
sbody += sdata;
});
sres.on("end", () => {
resolve(sres);
});
});
send_file_req.setHeader("content-type", "application/json");
send_file_req.write(JSON.stringify(json_data));
send_file_req.end();
}
else {
reject(`Received a non-200 response code. (${pres.statusCode}) (place file)\n${JSON.stringify(headers_place_file)}`);
}
});
});
place_file_req.write(raw);
place_file_req.end();
}
else {
reject(`Received a non-200 response code. (${res.statusCode}) (file holder)`);
}
});
});
file_url_holder_req.end();
});
return myPromise;
}
send_sms(to, text) {
const myPromise = new Promise((resolve, reject) => {
const data = {
'json': JSON.stringify({
"contact_value": to,
"contact_type": 2,
"message": text,
"read": 1, "message_direction": 2,
"message_type": 1,
"from_name": this.username,
"has_video": false,
"new": true,
"date": new Date().toISOString()
})
}
const request = https.request('https://www.textnow.com/api/users/' + this.username + '/messages', {
headers: {
...this.headers,
cookie: this.processCookies(this.cookies)
},
method: "POST"
});
request.on("response", response => {
let body = "";
response.on("data", data => {
body += data;
});
response.on("end", async () => {
if (response.statusCode == 200) {
this.reverseCookie(response.headers['set-cookie']);
if (this.delete_on_send) {
await this.delete(JSON.parse(body).id);
}
}
else {
console.log(response.statusCode);
}
resolve(body);
});
});
request.setHeader("content-type", "application/json")
request.write(JSON.stringify(data));
request.end();
});
return myPromise;
}
/**
*
* @param {Array} arr
* @returns {boolean}
*/
all(arr) {
for (let x = 0; x < arr.length; x++) {
if (!arr[x]) return false;
}
return true;
}
}
module.exports = Client;