-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetThreads.js
456 lines (428 loc) · 14.2 KB
/
getThreads.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
import WebSocket from "ws";
import axios from "axios";
import mqtt from "mqtt-packet";
import "dotenv/config";
import fs from "fs";
const args = process.argv.slice(2);
const cookies = process.env.COOKIES;
async function getClientId() {
const response = await axios.get("https://www.instagram.com/direct/", {
headers: {
authority: "www.instagram.com",
accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
"cache-control": "max-age=0",
cookie: cookies,
"sec-ch-prefers-color-scheme": "light",
"sec-ch-ua":
'"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-full-version-list":
'"Not.A/Brand";v="8.0.0.0", "Chromium";v="114.0.5735.133", "Google Chrome";v="114.0.5735.133"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"macOS"',
"sec-ch-ua-platform-version": '"13.2.1"',
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
"user-agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"viewport-width": "558",
},
});
const resp = response.data;
const clientId = resp.slice(resp.indexOf('{"clientID":')).split('"')[3];
const dtsg = resp.slice(resp.indexOf("DTSGInitialData")).split('"')[4];
const userId = resp.match(/"IG_USER_EIMU":"([^"]+)"/)?.[1];
return { clientId, dtsg, userId };
}
async function apiCall(cid, dtsg, cursor = null) {
const response = await axios.post(
"https://www.instagram.com/api/graphql/",
new URLSearchParams({
fb_dtsg: dtsg,
variables: JSON.stringify({
deviceId: cid,
requestId: 0,
requestPayload: JSON.stringify({
database: 1,
epoch_id: 0,
last_applied_cursor: cursor,
sync_params: JSON.stringify({}),
version: 9477666248971112,
}),
requestType: 1,
}),
doc_id: "6195354443842040",
}),
{
headers: {
authority: "www.instagram.com",
accept: "*/*",
"accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
"cache-control": "no-cache",
cookie: cookies,
origin: "https://www.instagram.com",
pragma: "no-cache",
referer: "https://www.instagram.com/",
"sec-ch-prefers-color-scheme": "dark",
"sec-ch-ua":
'"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-full-version-list":
'"Not.A/Brand";v="8.0.0.0", "Chromium";v="114.0.5735.133", "Google Chrome";v="114.0.5735.133"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"macOS"',
"sec-ch-ua-platform-version": '"13.2.1"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"x-ig-app-id": "936619743392459",
},
}
);
return response;
}
// construct the conversations from undecipherable data
function parseResponse(payload) {
const j = JSON.parse(payload);
// tasks we are interested in
let lsCalls = {
verifyContactRowExists: [],
addParticipantIdToGroupThread: [],
deleteThenInsertThread: [],
};
let userLookup = {};
let conversationParticipants = {};
let conversations = [];
// loop through the tasks
for (const item of j.step[2][2][2].slice(1)) {
// if we are interested in the task then add it to the lsCalls object
if (item[1][1] in lsCalls) {
lsCalls[item[1][1]].push(item[1].slice(2));
}
}
// major shout out to Radon Rosborough(username radian-software) and Scott Conway (username scottmconway) for their work in deciphering the lsCalls
// this parsing would not be possible without their repos
// https://github.com/scottmconway/unzuckify
// https://github.com/radian-software/unzuckify
// https://intuitiveexplanations.com/tech/messenger Radon's blog post on reverse engineering messenger. messenger and instagram use the same protocol
for (const item of lsCalls.verifyContactRowExists) {
const userId = item[0][1];
const name = item[3];
const username = item[item.length - 1];
userLookup[userId] = { name, username, userId };
}
for (const item of lsCalls.addParticipantIdToGroupThread) {
const threadId = item[0][1]; // in DMs is also the other user id
const userId = item[1][1]; // userId
// skip if userId is my own
if (userId === myUserId) continue;
// if threadId does not exist then create an empty set
if (!(threadId in conversationParticipants)) {
conversationParticipants[threadId] = new Set();
}
conversationParticipants[threadId].add(userLookup[userId]);
}
for (const item of lsCalls.deleteThenInsertThread) {
const lastSentTime = item[0][1];
const lastReadTime = item[1][1];
const lastMessage = item[2];
let groupName;
if (Array.isArray(item[3])) {
groupName = null;
} else {
groupName = item[3];
}
const threadId = item[7][1];
const lastAuthor = item[18][1];
// if threadId is not in conversationParticipants then continue
if (!(threadId in conversationParticipants)) continue;
// if groupName is null then set it to all the participants names
if (groupName === null) {
groupName = Array.from(conversationParticipants[threadId])
.map((x) => x.name)
.join(", ");
}
conversations.push({
threadId,
unread: Number(lastSentTime) > Number(lastReadTime),
lastReadTime,
lastSentTime,
lastMessage,
lastAuthor,
groupName,
participants: Array.from(conversationParticipants[threadId]),
});
}
return { newConversations: conversations, cursor: j.step[2][1][3][5] };
}
// get the initial conversations
async function initialConnection(cid, dtsg) {
const response = await apiCall(cid, dtsg);
const { newConversations, cursor } = await parseResponse(
response.data.data.lightspeed_web_request_for_igd.payload
);
return { newConversations, cursor };
}
// parse mqtt packet
// promisifies the mqtt parser to make it easier to use
function parseMqttPacket(data) {
const parser = mqtt.parser({
protocolVersion: 3,
});
return new Promise((resolve, reject) => {
parser.on("packet", (packet) => {
const j = JSON.parse(packet.payload);
resolve(j);
});
parser.on("error", (error) => {
reject(error);
});
parser.parse(data);
});
}
const { clientId, dtsg, userId: myUserId } = await getClientId();
let { cursor, newConversations: conversations } = await initialConnection(
clientId,
dtsg
);
const mqttSid = parseInt(Math.random().toFixed(16).split(".")[1]);
const ws = new WebSocket(
`wss://edge-chat.instagram.com/chat?sid=${mqttSid}&cid=${clientId}`,
{
origin: "https://www.instagram.com",
headers: {
Host: "edge-chat.instagram.com",
Connection: "Upgrade",
Pragma: "no-cache",
"Cache-Control": "no-cache",
Upgrade: "websocket",
Origin: "https://www.instagram.com",
"Sec-WebSocket-Version": "13",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
"User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
Cookie: cookies,
},
}
);
ws.on("error", function incoming(data) {
console.log("Error", data);
});
ws.on("open", function open() {
console.log("connected");
// initiate connection
ws.send(
mqtt.generate({
cmd: "connect",
protocolId: "MQIsdp",
clientId: "mqttwsclient",
protocolVersion: 3,
clean: true,
keepalive: 10,
username: JSON.stringify({
u: "userid", // doesnt seem to matter
s: mqttSid,
cp: 3,
ecp: 10,
chat_on: true,
fg: false,
d: clientId,
ct: "cookie_auth",
mqtt_sid: "",
aid: 936619743392459, // app id
st: [],
pm: [],
dc: "",
no_auto_fg: true,
gas: null,
pack: [],
php_override: "",
p: null,
a: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36",
aids: null,
}),
})
);
// send app settings
// need to wait for the ack before sending the subscribe
ws.send(
mqtt.generate({
cmd: "publish",
messageId: 1,
qos: 1,
topic: "/ls_app_settings",
payload: JSON.stringify({
ls_fdid: "",
ls_sv: "9477666248971112", // version id
}),
})
);
});
ws.on("message", function incoming(data) {
if (data.toString("hex") == "42020001") {
// ack for app settings
// subscribe to /ls_resp
ws.send(
mqtt.generate({
cmd: "subscribe",
qos: 1,
subscriptions: [
{
topic: "/ls_resp",
qos: 0,
},
],
messageId: 3,
})
);
// get messages
ws.send(
mqtt.generate({
cmd: "publish",
messageId: 6,
qos: 1,
dup: false,
retain: false,
topic: "/ls_req",
payload: JSON.stringify({
app_id: "936619743392459",
payload: JSON.stringify({
tasks: [
{
label: "145",
payload: JSON.stringify({
is_after: 0,
parent_thread_key: 0,
reference_thread_key: Number(
conversations[conversations.length - 1].threadId
),
reference_activity_timestamp:
conversations[conversations.length - 1].lastSentTime,
additional_pages_to_fetch: 0,
cursor: cursor,
messaging_tag: null,
sync_group: 1,
}),
queue_name: "trq",
task_id: 1,
failure_count: null,
},
],
epoch_id: Number(BigInt(Date.now()) << BigInt(22)),
version_id: "9477666248971112",
}),
request_id: 6,
type: 3,
}),
})
);
// not sure exactly what this does but it's required.
// my guess is it "subscribes to database 1"?
// may need similar code to get messages.
ws.send(
mqtt.generate({
cmd: "publish",
messageId: 5,
qos: 1,
dup: false,
retain: false,
topic: "/ls_req",
payload: JSON.stringify({
app_id: "936619743392459",
payload: JSON.stringify({
database: 1,
epoch_id: Number(BigInt(Date.now()) << BigInt(22)),
failure_count: null,
last_applied_cursor: cursor,
sync_params: null,
version: 9477666248971112,
}),
request_id: 5,
type: 2,
}),
})
);
} else if (data[0] != 0x42) {
// for some reason fb sends wrongly formatted packets for PUBACK.
// this causes mqtt-packet to throw an error.
// this is a hacky way to fix it.
parseMqttPacket(data).then((payload) => {
if (!payload) return;
// the broker sends 4 responses to the get messages command (request_id = 6)
// 1. ack
// 2. a response with a new cursor, the official client uses the new cursor to get more messages
// however, the new cursor is not needed to get more messages, as the old cursor still works
// not sure exactly what the new cursor is for, but it's not needed. the request_id is null
// 3. unknown response with a request_id of 6. has no information
// 4. the thread information. this is the only response that is needed. this packet has the text deleteThenInsertThread
if (
payload.request_id === null &&
payload.payload.includes("deleteThenInsertThread")
) {
console.log("got messages");
parseMqttPacket(data).then((payload) => {
const { newConversations } = parseResponse(payload.payload);
console.log(JSON.stringify(newConversations, null, 2));
conversations.push(...newConversations);
ws.send(
mqtt.generate({
cmd: "publish",
messageId: 6,
qos: 1,
dup: false,
retain: false,
topic: "/ls_req",
payload: JSON.stringify({
app_id: "936619743392459",
payload: JSON.stringify({
tasks: [
{
label: "145",
payload: JSON.stringify({
is_after: 0,
parent_thread_key: 0,
reference_thread_key: Number(
conversations[conversations.length - 1].threadId
),
reference_activity_timestamp:
conversations[conversations.length - 1].lastSentTime,
additional_pages_to_fetch: 0,
cursor: cursor,
messaging_tag: null,
sync_group: 1,
}),
queue_name: "trq",
task_id: 1,
failure_count: null,
},
],
epoch_id: Number(BigInt(Date.now()) << BigInt(22)),
version_id: "9477666248971112",
}),
request_id: 6,
type: 3,
}),
})
);
});
}
});
}
});
ws.on("close", function close() {
console.log("disconnected");
if (args.length === 0) return;
fs.writeFile(args[0], JSON.stringify(conversations, null, 2), (err) => {
if (err) {
console.error(err);
}
// file written successfully
console.log("file written");
});
});