forked from pishangujeniya/instagram-helper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InstagramHelper.js
644 lines (553 loc) · 25.4 KB
/
InstagramHelper.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/**
* Instagram Helper
*/
class InstagramHelper {
/**
* default constructor
*/
constructor() {
this.allMessagesItemsArray = [];
this.usersChatParticipants = [];
this.p_userId = this.getCookie("ds_user_id");
this.p_itemsIdArray = [];
if (localStorage.getItem('messages_ids') != undefined) {
this.p_itemsIdArray = localStorage.getItem('messages_ids').split(',');
} else {
localStorage.setItem('messages_ids', this.p_itemsIdArray);
}
this.deletedItemIdArray = [];
if (localStorage.getItem('deleted_messages_ids') != undefined) {
this.deletedItemIdArray = localStorage.getItem('deleted_messages_ids').split(',');
} else {
localStorage.setItem('deleted_messages_ids', this.deletedItemIdArray);
}
this.p_oldestCursor = "";
this.p_prevCursor = "";
this.getConsumerLibCommonsJs();
this.stopGettingMessages = false;
this.stopDeletingMessages = false;
}
syncWait = ms => {
const end = Date.now() + ms
while (Date.now() < end) continue
}
/**
* provides cookie value if exists else provides empty string
* @param {string} c_name cookie key name
*/
getCookie(c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
var c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
/**
* generates random integer between 1 and provided
* @param {number} maxNumber max number between which to generate random integer (default value is 10)
*/
getRandomIntegerBetween(maxNumber) {
if (maxNumber != undefined && maxNumber != null && maxNumber > 0) {
// its provided
} else {
maxNumber = 10;
}
return Math.floor((Math.random() * maxNumber) + 1);
}
/**
* provides the ConsumerLibCommon Js File
* @param {string} jsFileName default is d7e6aac102d8.js
*/
async getConsumerLibCommonsJs(jsFileName = "d7e6aac102d8.js") {
let consumerLibCommonsJsRequestUrl = "https://www.instagram.com/static/bundles/es6/ConsumerLibCommons.js/" + jsFileName;
let consumerLibCommonsJsRequestInit = {
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"pragma": "no-cache",
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "none",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1"
},
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
};
await fetch(
consumerLibCommonsJsRequestUrl,
consumerLibCommonsJsRequestInit
)
.then((response) => {
if (response.status != 200) {
console.error("Try again tomorrow");
} else {
return response.text();
}
})
.then((data) => {
let appIdVariableNames = [
"instagramFBAppId",
"instagramWebFBAppId",
"instagramWebDesktopFBAppId",
"igLiteAppId"
];
appIdVariableNames.forEach(singleppIdVariableName => {
let searchString = singleppIdVariableName + "='";
let indexOfSearchedStringVariableName = data.indexOf(searchString);
let valueData = data.substring(indexOfSearchedStringVariableName + searchString.length);
let singleAppIdValue = valueData.substring(0, valueData.indexOf("'"));
// console.warn(singleppIdVariableName + " = " + singleAppIdValue);
localStorage.setItem(singleppIdVariableName, singleAppIdValue);
});
});
}
/**
* Fetch the messages and its itemIds
*/
async getAllMessagesData(threadId) {
if (threadId == null || threadId == undefined) {
console.error("threadId must be passed");
return false;
}
let threadLink = "https://www.instagram.com/direct/t/" + threadId;
// if its first message ever sent then stop else continue
while (this.p_prevCursor != "MINCURSOR" && this.stopGettingMessages == false) {
var getMessageAPIUrl = "https://i.instagram.com/api/v1/direct_v2/threads/" + threadId + "/";
if (this.p_oldestCursor != undefined && this.p_oldestCursor != null && this.p_oldestCursor.length > 0) {
getMessageAPIUrl = getMessageAPIUrl + "?cursor=" + this.p_oldestCursor + "";
}
var getMessagesRequestInit = {
"credentials": "include",
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"pragma": "no-cache",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-ig-app-id": localStorage.getItem("instagramWebFBAppId"),
"x-ig-www-claim": sessionStorage.getItem("www-claim-v2"),
"x-requested-with": "XMLHttpRequest"
},
"referrer": threadLink,
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "GET",
"mode": "cors"
};
await fetch(
getMessageAPIUrl,
getMessagesRequestInit
)
.then((response) => {
if (response.status != 200) {
console.error("Try again tomorrow");
throw response.status;
} else {
return response.json();
}
})
.then((data) => {
// console.log(data);
console.log("getting messages...");
//#region Own Inviter Adding to Participants
let inviterChatParticipant = {
"pk": data.thread.inviter.pk,
"profile_pic_url": data.thread.inviter.profile_pic_url,
"full_name": data.thread.inviter.full_name,
"username": data.thread.inviter.username
}
let isChatParticipantAlreadyExists = false;
for (let index = 0; index < this.usersChatParticipants.length; index++) {
const singleUserChatParticipant = this.usersChatParticipants[index];
if (singleUserChatParticipant.pk == inviterChatParticipant.pk) {
isChatParticipantAlreadyExists = true;
break;
}
}
if (!isChatParticipantAlreadyExists) {
this.usersChatParticipants.push(inviterChatParticipant);
}
//#endregion
//#region Thread Participants adding
data.thread.users.forEach(element => {
let chatParticipant = {
"pk": element.pk,
"profile_pic_url": element.profile_pic_url,
"full_name": element.full_name,
"username": element.username
};
let isChatParticipantAlreadyExists = false;
for (let index = 0; index < this.usersChatParticipants.length; index++) {
const singleUserChatParticipant = this.usersChatParticipants[index];
if (singleUserChatParticipant.pk == element.pk) {
isChatParticipantAlreadyExists = true;
break;
}
}
if (!isChatParticipantAlreadyExists) {
this.usersChatParticipants.push(chatParticipant);
}
});
//#endregion
//#region Adding Messages
data.thread.items.forEach(element => {
var isExists = false;
for (let index = 0; index < this.allMessagesItemsArray.length; index++) {
const existingElement = this.allMessagesItemsArray[index];
if (existingElement.item_id.toString() == element.item_id.toString()) {
isExists = true;
break;
}
}
if (!isExists) {
this.allMessagesItemsArray.push(element);
}
});
//#endregion
data.thread.items.forEach(element => {
if (element.user_id.toString() == this.p_userId.toString()) {
if (!this.p_itemsIdArray.includes(element.item_id.toString())) {
this.p_itemsIdArray.push(element.item_id.toString());
}
}
this.allMessagesItemsArray.push(element);
});
this.p_oldestCursor = data.thread.oldest_cursor;
this.p_prevCursor = data.thread.prev_cursor;
})
.catch((error) => {
console.error(error);
return false;
});
}
localStorage.setItem('messages_ids', this.p_itemsIdArray);
console.warn("All Messages fetched, No More messages to fetch");
return true;
}
async getInboxRequest() {
var getInboxRequestUrl = "https://i.instagram.com/api/v1/direct_v2/inbox/?persistentBadging=true&folder=&limit=10&thread_message_limit=10";
var getInboxRequestInit = {
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"pragma": "no-cache",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site",
"x-ig-app-id": localStorage.getItem("instagramWebFBAppId"),
"x-ig-www-claim": sessionStorage.getItem("www-claim-v2")
},
"referrer": "https://www.instagram.com/",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
};
await fetch(
getInboxRequestUrl,
getInboxRequestInit
)
.then(async (response) => {
if (response.status != 200) {
console.error("Try again tomorrow");
} else {
return response.json();
}
})
.then(async (data) => {
console.log(data);
}).catch((error) => {
console.error(error);
});
}
async startUnsending(threadId = undefined, delay = 3500) {
if (threadId == null || threadId == undefined) {
var threadId = window.location.href.split('/')[5]; // Get the chat id automatically from the url, make sure a chat is currently active
console.warn("Starting deleting from thread Id : " + threadId);
}
console.warn("Inevitable");
let threadLink = "https://www.instagram.com/direct/t/" + threadId;
// if its first message ever sent then stop else continue
while (this.p_prevCursor != "MINCURSOR") {
var getMessageAPIUrl = "https://i.instagram.com/api/v1/direct_v2/threads/" + threadId + "/";
if (this.p_oldestCursor != undefined && this.p_oldestCursor != null && this.p_oldestCursor.length > 0) {
getMessageAPIUrl = getMessageAPIUrl + "?cursor=" + this.p_oldestCursor + "";
}
var getMessagesRequestInit = {
"credentials": "include",
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"pragma": "no-cache",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-ig-app-id": localStorage.getItem("instagramWebFBAppId"),
"x-ig-www-claim": sessionStorage.getItem("www-claim-v2"),
"x-requested-with": "XMLHttpRequest"
},
"referrer": threadLink,
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "GET",
"mode": "cors"
};
await fetch(
getMessageAPIUrl,
getMessagesRequestInit
)
.then(async (response) => {
if (response.status != 200) {
console.error("Try again tomorrow");
} else {
return response.json();
}
})
.then(async (data) => {
// console.log(data);
let itemIdsToDelete = [];
console.log("getting messages...");
data.thread.items.forEach(element => {
if (element.user_id.toString() == this.p_userId.toString()) {
if (!itemIdsToDelete.includes(element.item_id.toString())) {
itemIdsToDelete.push(element.item_id.toString());
}
}
});
//#region Deleting Messages
for (let itemIdIndex = 0; itemIdIndex < itemIdsToDelete.length; itemIdIndex++) {
const messageItemId = itemIdsToDelete[itemIdIndex];
var p_unsendRequestInitObj = {
"credentials": "include",
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded",
"pragma": "no-cache",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-csrftoken": this.getCookie("csrftoken"),
"x-ig-app-id": localStorage.getItem("instagramWebFBAppId"),
"x-ig-www-claim": sessionStorage.getItem("www-claim-v2"),
"x-requested-with": "XMLHttpRequest"
},
"referrer": threadLink,
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "POST",
"mode": "cors"
};
await fetch(
"https://i.instagram.com/api/v1/direct_v2/threads/" + threadId + "/items/" + messageItemId + "/delete/",
p_unsendRequestInitObj
).then((response) => {
if (response.status != 200) {
console.error("Some messages skipped");
} else {
console.info("Deleting...");
}
}).catch((error) => {
console.error(error);
});
this.syncWait(delay);
}
//#endregion Deleting Messages
this.p_oldestCursor = data.thread.oldest_cursor;
this.p_prevCursor = data.thread.prev_cursor;
})
.catch((error) => {
console.error(error);
});
}
console.warn("All messages deleted.");
return true;
}
async startUnsendingMedia(threadId = undefined, delay = 3500) {
if (threadId == null || threadId == undefined) {
var threadId = window.location.href.split('/')[5]; // Get the chat id automatically from the url, make sure a chat is currently active
console.warn("Starting deleting from thread Id : " + threadId);
}
console.warn("Inevitable");
let threadLink = "https://www.instagram.com/direct/t/" + threadId;
// if its first message ever sent then stop else continue
while (this.p_prevCursor != "MINCURSOR") {
var getMessageAPIUrl = "https://i.instagram.com/api/v1/direct_v2/threads/" + threadId + "/";
if (this.p_oldestCursor != undefined && this.p_oldestCursor != null && this.p_oldestCursor.length > 0) {
getMessageAPIUrl = getMessageAPIUrl + "?cursor=" + this.p_oldestCursor + "";
}
var getMessagesRequestInit = {
"credentials": "include",
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"pragma": "no-cache",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-ig-app-id": localStorage.getItem("instagramWebFBAppId"),
"x-ig-www-claim": sessionStorage.getItem("www-claim-v2"),
"x-requested-with": "XMLHttpRequest"
},
"referrer": threadLink,
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "GET",
"mode": "cors"
};
await fetch(
getMessageAPIUrl,
getMessagesRequestInit
)
.then(async (response) => {
if (response.status != 200) {
console.error("Try again tomorrow");
} else {
return response.json();
}
})
.then(async (data) => {
// console.log(data);
let itemIdsToDelete = [];
console.log("getting media...");
data.thread.items.forEach(element => {
// console.log("element is text " + JSON.stringify(element));
if (element.user_id.toString() == this.p_userId.toString()) {
if(element.item_type !== "text"){
if (!itemIdsToDelete.includes(element.item_id.toString())) {
itemIdsToDelete.push(element.item_id.toString());
}
}
}
});
//#region Deleting Messages
for (let itemIdIndex = 0; itemIdIndex < itemIdsToDelete.length; itemIdIndex++) {
const messageItemId = itemIdsToDelete[itemIdIndex];
var p_unsendRequestInitObj = {
"credentials": "include",
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded",
"pragma": "no-cache",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-csrftoken": this.getCookie("csrftoken"),
"x-ig-app-id": localStorage.getItem("instagramWebFBAppId"),
"x-ig-www-claim": sessionStorage.getItem("www-claim-v2"),
"x-requested-with": "XMLHttpRequest"
},
"referrer": threadLink,
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "POST",
"mode": "cors"
};
await fetch(
"https://i.instagram.com/api/v1/direct_v2/threads/" + threadId + "/items/" + messageItemId + "/delete/",
p_unsendRequestInitObj
).then((response) => {
if (response.status != 200) {
console.error("Some messages skipped");
} else {
console.info("Deleting...");
}
}).catch((error) => {
console.error(error);
});
this.syncWait(delay);
}
//#endregion Deleting Messages
this.p_oldestCursor = data.thread.oldest_cursor;
this.p_prevCursor = data.thread.prev_cursor;
})
.catch((error) => {
console.error(error);
});
}
console.warn("All media deleted.");
return true;
}
/**
* Deletes all the follow requests for private account
* @param {string} deleteButtonCSSClassName | provide the css class name of Delete button by Inspect Element
*/
async deleteAllFollowRequests(deleteButtonCSSClassName) {
let t = document.getElementsByClassName(deleteButtonCSSClassName);
for (let index = 0; index < t.length; index++) {
const element = t[index];
this.syncWait(1000);
element.click();
}
}
downloadMessagesDetails() {
this.downloadJsonFile(
{
"myUserId": this.p_userId,
"allMessagesItemsArray": this.allMessagesItemsArray,
"usersChatParticipants": this.usersChatParticipants,
},
"InstaGramHelperChatMessagesData"
);
}
/**
* Downloads JSON file from Object in Browser
* @param {*} jsonDataObject Json Object
* @param {string} fileNameExcludingExtension
*/
downloadJsonFile(jsonDataObject, fileNameExcludingExtension = 'data') {
const blob = new Blob(['\ufeff' + JSON.stringify(jsonDataObject)], {
type: 'text/json;charset=utf-8;'
});
const dwldLink = document.createElement('a');
const url = URL.createObjectURL(blob);
const isSafariBrowser = navigator.userAgent.indexOf('Safari') !== -1 &&
navigator.userAgent.indexOf('Chrome') === -1;
if (isSafariBrowser) {
// for safari
dwldLink.setAttribute('target', '_blank');
}
dwldLink.setAttribute('href', url);
dwldLink.setAttribute('download', fileNameExcludingExtension + '.json');
dwldLink.style.visibility = 'hidden';
document.body.appendChild(dwldLink);
dwldLink.click();
document.body.removeChild(dwldLink);
}
/**
* Downloads any type of file containing text in browser
* @param {*} text String Text of File
* @param {string} fileNameExcludingExtension File name without Extension
* @param {string} extension Extension of file with downloadTextFile
*/
downloadTextFile(text, fileNameExcludingExtension = 'data', extension = '.txt') {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', fileNameExcludingExtension + extension);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
}