-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.js
3666 lines (3217 loc) · 175 KB
/
main.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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name IG Helper
// @name:zh-TW IG小精靈
// @name:zh-CN IG小助手
// @name:ja IG助手
// @name:ko IG조수
// @namespace https://github.snkms.com/
// @version 2.39.6
// @description Downloading is possible for both photos and videos from posts, as well as for stories, reels or profile picture.
// @description:zh-TW 一鍵下載對方 Instagram 貼文中的相片、影片甚至是他們的限時動態、連續短片及大頭貼圖片!
// @description:zh-CN 一键下载对方 Instagram 帖子中的相片、视频甚至是他们的快拍、Reels及头像图片!
// @description:ja 投稿の写真と動画だけでなく、ストーリー、リール、プロフィール写真もダウンロードできます。
// @description:ko 게시물의 사진과 동영상뿐만 아니라 스토리, 릴 또는 프로필 사진도 다운로드할 수 있습니다.
// @description:ro Descărcarea este posibilă atât pentru fotografiile și videoclipurile din postări, cât și pentru storyuri, reels sau poze de profil.
// @author SN-Koarashi (5026)
// @match https://*.instagram.com/*
// @grant GM_info
// @grant GM_addStyle
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_getResourceText
// @grant GM_notification
// @grant GM_openInTab
// @connect i.instagram.com
// @connect raw.githubusercontent.com
// @require https://code.jquery.com/jquery-3.7.1.min.js#sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=
// @resource INTERNAL_CSS https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/style.css
// @resource LOCALE_MANIFEST https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/locale/manifest.json
// @supportURL https://github.com/SN-Koarashi/ig-helper/
// @contributionURL https://ko-fi.com/snkoarashi
// @icon https://www.google.com/s2/favicons?domain=www.instagram.com&sz=32
// @compatible firefox >= 100
// @compatible chrome >= 100
// @compatible edge >= 100
// @license GPL-3.0-only
// @run-at document-idle
// @downloadURL https://update.greasyfork.org/scripts/404535/IG%20Helper.user.js
// @updateURL https://update.greasyfork.org/scripts/404535/IG%20Helper.meta.js
// ==/UserScript==
(function($) {
'use strict';
/******** USER SETTINGS ********/
// !!! DO NOT CHANGE THIS AREA !!!
// PLEASE CHANGE SETTING WITH MENU
const USER_SETTING = {
'CHECK_UPDATE': true,
'AUTO_RENAME': true,
'RENAME_PUBLISH_DATE': true,
'DISABLE_VIDEO_LOOPING': false,
'HTML5_VIDEO_CONTROL': false,
'REDIRECT_CLICK_USER_STORY_PICTURE': false,
'FORCE_FETCH_ALL_RESOURCES': false,
'DIRECT_DOWNLOAD_VISIBLE_RESOURCE': false,
'DIRECT_DOWNLOAD_ALL': false,
'MODIFY_VIDEO_VOLUME': false,
'SCROLL_BUTTON': true,
'FORCE_RESOURCE_VIA_MEDIA': false,
'USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT': false,
'NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST': false,
'SKIP_VIEW_STORY_CONFIRM': false
};
const CHILD_NODES = ['RENAME_PUBLISH_DATE', 'USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT', 'NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST'];
var VIDEO_VOLUME = (GM_getValue('G_VIDEO_VOLUME'))?GM_getValue('G_VIDEO_VOLUME'):1;
var TEMP_FETCH_RATE_LIMIT = false;
var RENAME_FORMAT = (GM_getValue('G_RENAME_FORMAT'))? GM_getValue('G_RENAME_FORMAT') : '%USERNAME%-%SOURCE_TYPE%-%SHORTCODE%-%YEAR%%MONTH%%DAY%_%HOUR%%MINUTE%%SECOND%_%ORIGINAL_NAME_FIRST%';
/*******************************/
// Icon download by https://www.flaticon.com/authors/pixel-perfect
const SVG = {
DOWNLOAD: '<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><g><path d="M382.56,233.376C379.968,227.648,374.272,224,368,224h-64V16c0-8.832-7.168-16-16-16h-64c-8.832,0-16,7.168-16,16v208h-64 c-6.272,0-11.968,3.68-14.56,9.376c-2.624,5.728-1.6,12.416,2.528,17.152l112,128c3.04,3.488,7.424,5.472,12.032,5.472 c4.608,0,8.992-2.016,12.032-5.472l112-128C384.192,245.824,385.152,239.104,382.56,233.376z"/></g></g><g><g><path d="M432,352v96H80v-96H16v128c0,17.696,14.336,32,32,32h416c17.696,0,32-14.304,32-32V352H432z"/></g></g>',
NEW_TAB: '<svg width="16" height="16" viewBox="3 3 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M20 14a1 1 0 0 0-1 1v3.077c0 .459-.022.57-.082.684a.363.363 0 0 1-.157.157c-.113.06-.225.082-.684.082H5.923c-.459 0-.571-.022-.684-.082a.363.363 0 0 1-.157-.157c-.06-.113-.082-.225-.082-.684L4.999 5.5a.5.5 0 0 1 .5-.5l3.5.005a1 1 0 1 0 .002-2L5.501 3a2.5 2.5 0 0 0-2.502 2.5v12.577c0 .76.083 1.185.32 1.627.223.419.558.753.977.977.442.237.866.319 1.627.319h12.154c.76 0 1.185-.082 1.627-.319.419-.224.753-.558.977-.977.237-.442.319-.866.319-1.627V15a1 1 0 0 0-1-1zm-2-9.055v-.291l-.39.09A10 10 0 0 1 15.36 5H14a1 1 0 1 1 0-2l5.5.003a1.5 1.5 0 0 1 1.5 1.5V10a1 1 0 1 1-2 0V8.639c0-.757.086-1.511.256-2.249l.09-.39h-.295a10 10 0 0 1-1.411 1.775l-5.933 5.932a1 1 0 0 1-1.414-1.414l5.944-5.944A10 10 0 0 1 18 4.945z" fill="currentColor"/></svg>',
THUMBNAIL: '<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="512" viewBox="0 0 24 24" width="512"><circle cx="8.25" cy="5.25" r=".5"/><path d="m8.25 6.5c-.689 0-1.25-.561-1.25-1.25s.561-1.25 1.25-1.25 1.25.561 1.25 1.25-.561 1.25-1.25 1.25zm0-1.5c-.138 0-.25.112-.25.25 0 .275.5.275.5 0 0-.138-.112-.25-.25-.25z"/><path d="m7.25 11.25 2-2.5 2.25 1.5 2.25-3.5 3 4.5z"/><path d="m16.75 12h-9.5c-.288 0-.551-.165-.676-.425s-.09-.568.09-.793l2-2.5c.243-.304.678-.372 1.002-.156l1.616 1.077 1.837-2.859c.137-.212.372-.342.625-.344.246-.026.49.123.63.334l3 4.5c.153.23.168.526.037.77-.13.244-.385.396-.661.396zm-4.519-1.5h3.118l-1.587-2.381zm-3.42 0h1.712l-1.117-.745z"/><path d="m22.25 14h-2.756c-.778 0-1.452.501-1.676 1.247l-.859 2.862c-.16.533-.641.891-1.197.891h-7.524c-.556 0-1.037-.358-1.197-.891l-.859-2.861c-.224-.747-.897-1.248-1.676-1.248h-2.756c-.965 0-1.75.785-1.75 1.75v5.5c0 1.517 1.233 2.75 2.75 2.75h18.5c1.517 0 2.75-1.233 2.75-2.75v-5.5c0-.965-.785-1.75-1.75-1.75z"/><path d="m4 12c-.552 0-1-.448-1-1v-8c0-1.654 1.346-3 3-3h12c1.654 0 3 1.346 3 3v8c0 .552-.448 1-1 1s-1-.448-1-1v-8c0-.551-.449-1-1-1h-12c-.551 0-1 .449-1 1v8c0 .552-.448 1-1 1z"/></svg>',
CLOSE: '<svg width="26" height="26" xmlns="http://www.w3.org/2000/svg" id="bold" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="m14.828 12 5.303-5.303c.586-.586.586-1.536 0-2.121l-.707-.707c-.586-.586-1.536-.586-2.121 0l-5.303 5.303-5.303-5.304c-.586-.586-1.536-.586-2.121 0l-.708.707c-.586.586-.586 1.536 0 2.121l5.304 5.304-5.303 5.303c-.586.586-.586 1.536 0 2.121l.707.707c.586.586 1.536.586 2.121 0l5.303-5.303 5.303 5.303c.586.586 1.536.586 2.121 0l.707-.707c.586-.586.586-1.536 0-2.121z"></path></svg>'
};
const checkInterval = 250;
const style = GM_getResourceText("INTERNAL_CSS");
const locale_manifest = JSON.parse(GM_getResourceText("LOCALE_MANIFEST"));
var GM_menuId = [];
var locale = {};
var lang = GM_getValue('lang') || navigator.language || navigator.userLanguage;
var currentURL = location.href;
var firstStarted = false;
var pageLoaded = false;
var GL_logger = [];
var GL_referrer;
var GL_postPath;
var GL_username;
var GL_repeat;
var GL_dataCache = {
stories: {},
highlights: {}
};
var GL_observer = new MutationObserver(function (mutation, owner) {
onReadyMyDW();
});
initSettings();
GM_addStyle(style);
registerMenuCommand();
getTranslationText(lang).then((res)=>{
locale[lang] = res;
repaintingTranslations();
registerMenuCommand();
checkingScriptUpdate(300);
}).catch((err)=>{
registerMenuCommand();
checkingScriptUpdate(300);
if(!lang.startsWith('en')){
console.error('getTranslationText catch error:', err);
}
});
// Main Timer
var timer = setInterval(function(){
// page loading or unnecessary route
if($('div#splash-screen').length > 0 && !$('div#splash-screen').is(':hidden') ||
location.pathname.match(/^\/(explore(\/.*)?|challenge\/?.*|direct\/?.*|qr\/?|accounts\/.*|emails\/.*|language\/?.*?|your_activity\/?.*|settings\/help(\/.*)?$)$/ig) ||
!location.hostname.startsWith('www.')
){
pageLoaded = false;
return;
}
if(currentURL != location.href || !firstStarted || !pageLoaded){
console.log('Main Timer', 'trigging');
clearInterval(GL_repeat);
pageLoaded = false;
firstStarted = true;
currentURL = location.href;
GL_observer.disconnect();
if(location.href.startsWith("https://www.instagram.com/p/") || location.pathname.match(/^\/(.*?)\/(p|reel)\//ig) || location.href.startsWith("https://www.instagram.com/reel/")){
GL_dataCache.stories = {};
GL_dataCache.highlights = {};
logger('isDialog');
// This is a delayed function call that prevents the dialog element from appearing before the function is called.
var dialogTimer = setInterval(()=>{
// body > div[id^="mount"] section nav + div > article << (mobile page in single post) >>
// section:visible > main > div > div > div > div > div > hr << (single foreground post in page, non-floating // <hr> element here is literally the line beneath poster's username) >>
// section:visible > main > div > div > article > div > div > div > div > div > header (is the same as above, except that this is on the route of the /{username}/p/{shortcode} structure)
// section:visible > main > div > div.xdt5ytf << (former CSS selector for single foreground post in page, non-floating) >>
// <hr> is much more unique element than "div.xdt5ytf"
if($(`body > div[class]:not([id^="mount"]) div div[role="dialog"] article,
section:visible > main > div > div > div > div > div > hr,
body > div[id^="mount"] section nav + div > article,
section:visible > main > div > div > article > div > div > div > div > div > header
`).length > 0){
clearInterval(dialogTimer);
// This is to prevent the detection of the "Modify Video Volume" setting from being too slow.
setTimeout(()=>{
onReadyMyDW(false);
}, 15);
}
},100);
pageLoaded = true;
}
if(location.href.startsWith("https://www.instagram.com/reels/")){
logger('isReels');
setTimeout(()=>{
onReels(false);
},150);
pageLoaded = true;
}
if(location.href.split("?")[0] == "https://www.instagram.com/"){
GL_dataCache.stories = {};
GL_dataCache.highlights = {};
let hasReferrer = GL_referrer?.match(/^\/(stories|highlights)\//ig) != null;
logger('isHomepage', hasReferrer);
setTimeout(()=>{
onReadyMyDW(false, hasReferrer);
const element = $('div[id^="mount"] > div > div div > section > main div:not([class]):not([style]) > div > article')?.parent()[0];
if(element){
GL_observer.observe(element, {
childList: true
});
}
},150);
pageLoaded = true;
}
if($('header > *[class]:first-child img[alt]').length && location.pathname.match(/^(\/)([0-9A-Za-z\.\-_]+)\/?(tagged|reels|saved)?\/?$/ig) && !location.pathname.match(/^(\/explore\/?$|\/stories(\/.*)?$|\/p\/)/ig)) {
logger('isProfile');
setTimeout(()=>{
onProfileAvatar(false);
},150);
pageLoaded = true;
}
if(!pageLoaded){
// Call Instagram stories function
if(location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/highlights\/)/ig)){
GL_dataCache.highlights = {};
logger('isHighlightsStory');
onHighlightsStory(false);
GL_repeat = setInterval(()=>{
onHighlightsStoryThumbnail(false);
},checkInterval);
if($(".IG_DWHISTORY").length){
setTimeout(()=>{
if(USER_SETTING.SKIP_VIEW_STORY_CONFIRM){
var $viewStoryButton = $('div[id^="mount"] section:last-child > div > div div[role="button"]').filter(function(){
return $(this).children().length === 0 && this.textContent.trim() !== "";
});
$viewStoryButton?.click();
}
pageLoaded = true;
},150);
}
}
else if(location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/)/ig)){
logger('isStory');
/*
*
* $('body div[id^="mount"] > div > div > div[class]').length >= 2 &&
* $('body div[id^="mount"] > div > div > div[class]').last().find('svg > path[d^="M16.792"], svg > path[d^="M34.6 3.1c-4.5"]').length > 0 &&
* $('body div[id^="mount"] > div > div > div[class]').last().find('svg > polyline + line').length > 0
*
*/
if($('div[id^="mount"] section > div > a[href="/"]').length > 0){
$('.IG_DWSTORY').remove();
$('.IG_DWNEWTAB').remove();
if($('.IG_DWSTORY_THUMBNAIL').length){
$('.IG_DWSTORY_THUMBNAIL').remove();
}
onStory(false);
// Prevent buttons from being eaten by black holes sometimes
setTimeout(()=>{
onStory(false);
}, 150);
}
if($(".IG_DWSTORY").length){
setTimeout(()=>{
if(USER_SETTING.SKIP_VIEW_STORY_CONFIRM){
var $viewStoryButton = $('div[id^="mount"] section:last-child > div > div div[role="button"]').filter(function(){
return $(this).children().length === 0 && this.textContent.trim() !== "";
});
$viewStoryButton?.click();
}
pageLoaded = true;
},150);
}
}
else{
pageLoaded = false;
// Remove icons
// Remove icons
if($('.IG_DWSTORY').length){
$('.IG_DWSTORY').remove();
}
if($('.IG_DWNEWTAB').length){
$('.IG_DWNEWTAB').remove();
}
if($('.IG_DWSTORY_THUMBNAIL').length){
$('.IG_DWSTORY_THUMBNAIL').remove();
}
if($('.IG_DWHISTORY').length){
$('.IG_DWHISTORY').remove();
}
if($('.IG_DWHINEWTAB').length){
$('.IG_DWHINEWTAB').remove();
}
if($('.IG_DWHISTORY_THUMBNAIL').length){
$('.IG_DWHISTORY_THUMBNAIL').remove();
}
}
}
checkingScriptUpdate(300);
GL_referrer = new URL(location.href).pathname;
}
},checkInterval);
/**
* onProfileAvatar
* Trigger user avatar download event or button display event.
*
* @param {Boolean} isDownload - Check if it is a download operation
* @return {void}
*/
async function onProfileAvatar(isDownload){
if(isDownload){
updateLoadingBar(true);
let date = new Date().getTime();
let timestamp = Math.floor(date / 1000);
let username = location.pathname.replaceAll(/(reels|tagged)\/$/ig,'').split('/').filter(s => s.length > 0).at(-1);
let userInfo = await getUserId(username);
try{
let dataURL = await getUserHighSizeProfile(userInfo.user.pk);
saveFiles(dataURL,username,"avatar",timestamp,'jpg');
}
catch(err){
saveFiles(userInfo.user.profile_pic_url,username,"avatar",timestamp,'jpg');
}
updateLoadingBar(false);
}
else{
// Add the profile download button
if(!$('.IG_DWPROFILE').length){
let profileTimer = setInterval(()=>{
if($('.IG_DWPROFILE').length){
clearInterval(profileTimer);
return;
}
$('header > *[class]:first-child img[alt][draggable]').parent().parent().append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_DWPROFILE">${SVG.DOWNLOAD}</div>`);
$('header > *[class]:first-child img[alt][draggable]').parent().parent().css('position','relative');
$('header > *[class]:first-child img[alt]:not([draggable])').parent().parent().parent().append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_DWPROFILE">${SVG.DOWNLOAD}</div>`);
$('header > *[class]:first-child img[alt]:not([draggable])').parent().parent().parent().css('position','relative');
},150);
}
}
}
/**
* onHighlightsStory
* Trigger user's highlight download event or button display event.
*
* @param {Boolean} isDownload - Check if it is a download operation
* @param {Boolean} isPreview - Check if it is need to open new tab
* @return {void}
*/
async function onHighlightsStory(isDownload, isPreview){
if(isDownload){
let date = new Date().getTime();
let timestamp = Math.floor(date / 1000);
let highlightId = location.href.replace(/\/$/ig,'').split('/').at(-1);
let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length ||
$('body > div section:visible > div > div:not([class]) > div > div div.x1ned7t2.x78zum5 div.x1caxmr6').length ||
$('body > div div:not([hidden]) section:visible > div div[style]:not([class]) > div').find('div div.x1ned7t2.x78zum5 div.x1caxmr6').length;
let username = "";
let target = 0;
updateLoadingBar(true);
if(GL_dataCache.highlights[highlightId]){
logger('Fetch from memory cache:', highlightId);
let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex-nowIndex];
}
else{
let highStories = await getHighlightStories(highlightId);
let totIndex = highStories.data.reels_media[0].items.length;
username = highStories.data.reels_media[0].owner.username;
target = highStories.data.reels_media[0].items[totIndex-nowIndex];
GL_dataCache.highlights[highlightId] = highStories;
}
if(USER_SETTING.RENAME_PUBLISH_DATE){
timestamp = target.taken_at_timestamp;
}
if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LIMIT){
let result = await getMediaInfo(target.id);
if(result.status === 'ok'){
if(result.items[0].video_versions){
if(isPreview){
openNewTab(result.items[0].video_versions[0].url);
}
else{
saveFiles(result.items[0].video_versions[0].url, username,"highlights",timestamp,'mp4', highlightId);
}
}
else{
if(isPreview){
openNewTab(result.items[0].image_versions2.candidates[0].url);
}
else{
saveFiles(result.items[0].image_versions2.candidates[0].url, username,"highlights",timestamp,'jpg', highlightId);
}
}
}
else{
if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT){
delete GL_dataCache.highlights[highlightId];
TEMP_FETCH_RATE_LIMIT = true;
onHighlightsStory(true, isPreview);
}
else{
alert('Fetch failed from Media API. API response message: ' + result.message);
}
logger(result);
}
}
else{
if(target.is_video){
if(isPreview){
openNewTab(target.video_resources.at(-1).src,username);
}
else{
saveFiles(target.video_resources.at(-1).src,username,"highlights",timestamp,'mp4', highlightId);
}
}
else{
if(isPreview){
openNewTab(target.display_resources.at(-1).src,username);
}
else{
saveFiles(target.display_resources.at(-1).src,username,"highlights",timestamp,'jpg', highlightId);
}
}
TEMP_FETCH_RATE_LIMIT = false;
}
updateLoadingBar(false);
}
else{
// Add the stories download button
if(!$('.IG_DWHISTORY').length){
let $element = null;
// Default detecter (section layout mode)
if($('body > div section._ac0a').length > 0){
$element = $('body > div section:visible._ac0a');
}
else{
$element = $('body > div section:visible > div > div[style]:not([class])');
$element.css('position','relative');
}
// Detecter for div layout mode
if($element.length === 0){
let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
let nowSize = 0;
$$element.each(function(){
if($(this).width() > nowSize){
nowSize = $(this).width();
$element = $(this).children('div').first();
}
});
}
if($element != null){
//$element.css('position','relative');
$element.append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_DWHISTORY">${SVG.DOWNLOAD}</div>`);
$element.append(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="IG_DWHINEWTAB">${SVG.NEW_TAB}</div>`);
//// Modify video volume
//if(USER_SETTING.MODIFY_VIDEO_VOLUME){
// $element.find('video').each(function(){
// $(this).on('play playing', function(){
// if(!$(this).data('modify')){
// $(this).attr('data-modify', true);
// this.volume = VIDEO_VOLUME;
// logger('(highlight) Added video event listener #modify');
// }
// });
// });
//}
// Make sure to first remove thumbnail button if still exists and highlight is a picture
$element.find('img[referrerpolicy]').each(function(){
$(this).on('load',function(){
if(!$(this).data('remove-thumbnail')){
if($element.find('.IG_DWHISTORY_THUMBNAIL').length === 0){
$(this).attr('data-remove-thumbnail', true);
$('.IG_DWHISTORY_THUMBNAIL').remove();
logger('(highlight) Manually removing thumbnail button');
}
else{
$(this).attr('data-remove-thumbnail', true);
logger('(highlight) Thumbnail button is not present for this picture');
}
}
});
});
// Try to use event listener 'timeupdate' in order to detect if highlight is a video
//$element.find('video').each(function(){
// $(this).on('timeupdate',function(){
// if(!$(this).data('modify-thumbnail')){
// if($element.find('.IG_DWHISTORY_THUMBNAIL').length === 0){
// $(this).attr('data-modify-thumbnail', true);
// onHighlightsStoryThumbnail(false);
// logger('(highlight) Manually inserting thumbnail button');
// }
// else{
// $(this).attr('data-modify-thumbnail', true);
// logger('(highlight) Thumbnail button already inserted');
// }
// }
// });
//});
}
}
}
}
/**
* onHighlightsStoryThumbnail
* Trigger user's highlight video thumbnail download event or button display event.
*
* @param {Boolean} isDownload - Check if it is a download operation
* @return {void}
*/
async function onHighlightsStoryThumbnail(isDownload){
if(isDownload){
let date = new Date().getTime();
let timestamp = Math.floor(date / 1000);
let highlightId = location.href.replace(/\/$/ig,'').split('/').at(-1);
let username = "";
let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length ||
$('body > div section:visible > div > div:not([class]) > div > div div.x1ned7t2.x78zum5 div.x1caxmr6').length ||
$('body > div div:not([hidden]) section:visible > div div[style]:not([class]) > div').find('div div.x1ned7t2.x78zum5 div.x1caxmr6').length;
let target = "";
updateLoadingBar(true);
if(GL_dataCache.highlights[highlightId]){
logger('Fetch from memory cache:', highlightId);
let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex-nowIndex];
}
else{
let highStories = await getHighlightStories(highlightId);
let totIndex = highStories.data.reels_media[0].items.length;
username = highStories.data.reels_media[0].owner.username;
target = highStories.data.reels_media[0].items[totIndex-nowIndex];
GL_dataCache.highlights[highlightId] = highStories;
}
if(USER_SETTING.RENAME_PUBLISH_DATE){
timestamp = target.taken_at_timestamp;
}
if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LIMIT){
let result = await getMediaInfo(target.id);
if(result.status === 'ok'){
saveFiles(result.items[0].image_versions2.candidates[0].url, username,"highlights",timestamp,'jpg',highlightId);
}
else{
if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT){
delete GL_dataCache.highlights[highlightId];
TEMP_FETCH_RATE_LIMIT = true;
onHighlightsStoryThumbnail(true);
}
else{
alert('Fetch failed from Media API. API response message: ' + result.message);
}
logger(result);
}
}
else{
saveFiles(target.display_resources.at(-1).src,username,"highlights",timestamp,'jpg', highlightId);
TEMP_FETCH_RATE_LIMIT= false;
}
updateLoadingBar(false);
}
else{
if($('body > div section video.xh8yej3').length){
// Add the stories thumbnail download button
if(!$('.IG_DWHISTORY_THUMBNAIL').length){
let $element = null;
// Default detecter (section layout mode)
if($('body > div section._ac0a').length > 0){
$element = $('body > div section:visible._ac0a');
}
else{
$element = $('body > div section:visible > div > div[style]:not([class])');
$element.css('position','relative');
}
// Detecter for div layout mode
if($element.length === 0){
let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
let nowSize = 0;
$$element.each(function(){
if($(this).width() > nowSize){
nowSize = $(this).width();
$element = $(this).children('div').first();
}
});
}
if($element != null){
$element.append(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWHISTORY_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
}
}
}
else{
$('.IG_DWHISTORY_THUMBNAIL').remove();
}
}
}
/**
* onStory
* Trigger user's story download event or button display event.
*
* @param {Boolean} isDownload - Check if it is a download operation
* @param {Boolean} isForce - Check if downloading directly from API instead of cache
* @param {Boolean} isPreview - Check if it is need to open new tab
* @return {void}
*/
async function onStory(isDownload,isForce,isPreview){
if(isDownload){
let date = new Date().getTime();
let timestamp = Math.floor(date / 1000);
let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split("/").filter(s => s.length > 0).at(1);
updateLoadingBar(true);
if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LIMIT){
let mediaId = null;
let userInfo = await getUserId(username);
let userId = userInfo.user.pk;
let stories = await getStories(userId);
let urlID = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
/*
let latest_reel_media = stories.data.reels_media[0].latest_reel_media;
let last_seen = stories.data.reels_media[0].seen;
logger(stories);
if(urlID == null){
mediaId = stories.data.reels_media[0].items.filter(function(item, index){
return item.taken_at_timestamp === last_seen && item.taken_at_timestamp !== latest_reel_media || last_seen === latest_reel_media && index === 0;
})?.at(0)?.id;
logger('nula', mediaId);
}
else{
stories.data.reels_media[0].items.forEach(item => {
if(item.id == urlID){
mediaId = item.id;
}
});
}
*/
stories.data.reels_media[0].items.forEach(item => {
if(item.id == urlID){
mediaId = item.id;
}
});
if(mediaId == null){
let $header = $('body > div section:visible a[href^="/'+(username)+'"] span').filter(function(){
return $(this).children().length === 0 && $(this).find('svg').length === 0 && $(this).text()?.toLowerCase() === username?.toLowerCase();
}).parents('div:not([class]):not([style])').filter(function(){
return $(this).text()?.toLowerCase() !== username?.toLowerCase()
}).filter(function(){
return $(this).children().length > 1
}).first();
$header.children().filter(function(){
return $(this).height() < 10
}).first().children().each(function(index){
if($(this).children().length > 0){
mediaId = stories.data.reels_media[0].items[index].id;
}
});
}
if(mediaId == null){
// appear in from profile page to story page
$('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
if($(this).hasClass('x1lix1fw')){
if($(this).children().length > 0){
mediaId = stories.data.reels_media[0].items[index].id;
}
}
});
// appear in from home page to story page
$('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
if($(this).children().hasClass('_ac3q')){
mediaId = stories.data.reels_media[0].items[index].id;
}
});
}
if(mediaId == null){
mediaId = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
}
let result = await getMediaInfo(mediaId);
if(USER_SETTING.RENAME_PUBLISH_DATE){
timestamp = result.items[0].taken_at;
}
if(result.status === 'ok'){
if(result.items[0].video_versions){
if(isPreview){
openNewTab(result.items[0].video_versions[0].url);
}
else{
saveFiles(result.items[0].video_versions[0].url, username,"stories",timestamp,'mp4',mediaId);
}
}
else{
if(isPreview){
openNewTab(result.items[0].image_versions2.candidates[0].url);
}
else{
saveFiles(result.items[0].image_versions2.candidates[0].url, username,"stories",timestamp,'jpg',mediaId);
}
}
}
else{
if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT){
TEMP_FETCH_RATE_LIMIT = true;
onStory(isDownload,isForce,isPreview);
}
else{
alert('Fetch failed from Media API. API response message: ' + result.message);
}
logger(result);
}
updateLoadingBar(false);
return;
}
if($('body > div section:visible video[playsinline]').length > 0){
// Download stories if it is video
let type = "mp4";
let videoURL = "";
let targetURL = location.pathname.replace(/\/$/ig,'').split("/").at(-1);
let mediaId = null;
if(GL_dataCache.stories[username] && !isForce){
logger('Fetch from memory cache:', username);
GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
if(item.id == targetURL){
videoURL = item.video_resources[0].src;
if(USER_SETTING.RENAME_PUBLISH_DATE){
timestamp = item.taken_at_timestamp;
mediaId = item.id;
}
}
});
if(videoURL.length == 0){
logger('Memory cache not found, try fetch from API:', username);
onStory(true,true);
return;
}
}
else{
let userInfo = await getUserId(username);
let userId = userInfo.user.pk;
let stories = await getStories(userId);
stories.data.reels_media[0].items.forEach(item => {
if(item.id == targetURL){
videoURL = item.video_resources[0].src;
if(USER_SETTING.RENAME_PUBLISH_DATE){
timestamp = item.taken_at_timestamp;
mediaId = item.id;
}
}
});
// GitHub issue #4: thinkpad4
if(videoURL.length == 0){
let $header = $('body > div section:visible a[href^="/'+(username)+'"] span').filter(function(){
return $(this).children().length === 0 && $(this).find('svg').length === 0 && $(this).text()?.toLowerCase() === username?.toLowerCase();
}).parents('div:not([class]):not([style])').filter(function(){
return $(this).text()?.toLowerCase() !== username?.toLowerCase()
}).filter(function(){
return $(this).children().length > 1
}).first();
$header.children().filter(function(){
return $(this).height() < 10
}).first().children().each(function(index){
if($(this).children().length > 0){
videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
if(USER_SETTING.RENAME_PUBLISH_DATE){
timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
mediaId = stories.data.reels_media[0].items[index].id;
}
}
});
if(videoURL.length == 0){
// appear in from profile page to story page
$('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
if($(this).hasClass('x1lix1fw')){
if($(this).children().length > 0){
videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
if(USER_SETTING.RENAME_PUBLISH_DATE){
timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
mediaId = stories.data.reels_media[0].items[index].id;
}
}
}
});
// appear in from home page to story page
$('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
if($(this).children().hasClass('_ac3q')){
videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
if(USER_SETTING.RENAME_PUBLISH_DATE){
timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
mediaId = stories.data.reels_media[0].items[index].id;
}
}
});
}
}
GL_dataCache.stories[username] = stories;
}
if(videoURL.length == 0){
alert(_i18n("NO_VID_URL"));
}
else{
if(isPreview){
openNewTab(videoURL);
}
else{
saveFiles(videoURL,username,"stories",timestamp,type, mediaId);
}
}
}
else{
// Download stories if it is image
let srcset = $('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').attr('srcset')?.split(',')[0]?.split(' ')[0];
let link = (srcset)?srcset:$('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').filter(function(){
return $(this).parents('a').length === 0 && $(this).width() === $(this).parent().width();
}).attr('src');
if(!link){
// _aa63 mean stories picture in stories page (not avatar)
let $element = $('body > div section:visible img._aa63');
link = ($element.attr('srcset'))?$element.attr('srcset')?.split(',')[0]?.split(' ')[0]:$element.attr('src');
}
if(USER_SETTING.RENAME_PUBLISH_DATE){
timestamp = new Date($('body > div section:visible time[datetime][class]').first().attr('datetime')).getTime();
}
let downloadLink = link;
let type = 'jpg';
if(isPreview){
openNewTab(downloadLink);
}
else{
saveFiles(downloadLink,username,"stories",timestamp,type, getStoryId(downloadLink) ?? "");
}
}
TEMP_FETCH_RATE_LIMIT = false;
updateLoadingBar(false);
}
else{
// Add the stories download button
let style = "position: absolute;right:-40px;top:15px;padding:5px;line-height:1;background:#fff;border-radius: 5px;cursor:pointer;";
if(!$('.IG_DWSTORY').length){
GL_dataCache.stories = {};
let $element = null;
// Default detecter (section layout mode)
if($('body > div section._ac0a').length > 0){
$element = $('body > div section:visible._ac0a');
}
// detecter (single story layout mode)
else{
$element = $('body > div section:visible > div > div[style]:not([class])');
$element.css('position','relative');
}
if($element.length === 0){
$element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('section:visible > div > div[style]:not([class])');
$element.css('position','relative');
}
if($element.length === 0){
$element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('section:visible > div div[style]:not([class]) > div:not([data-visualcompletion="loading-state"])');
$element.css('position','relative');
}
// Detecter for div layout mode
if($element.length === 0){
let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
let nowSize = 0;
$$element.each(function(){
if($(this).width() > nowSize){
nowSize = $(this).width();
$element = $(this).children('div').first();
}
});
}
if($element != null){
$element.first().css('position','relative');
$element.first().append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_DWSTORY">${SVG.DOWNLOAD}</div>`);
$element.first().append(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="IG_DWNEWTAB">${SVG.NEW_TAB}</div>`);
// Modify video volume
//if(USER_SETTING.MODIFY_VIDEO_VOLUME){
// $element.find('video').each(function(){
// $(this).on('play playing', function(){
// if(!$(this).data('modify')){
// $(this).attr('data-modify', true);
// this.volume = VIDEO_VOLUME;
// logger('(story) Added video event listener #modify');
// }
// });
// });
//}
// Make sure to first remove thumbnail button if still exists and story is a picture
$element.find('img[referrerpolicy]').each(function(){
$(this).on('load',function(){
if(!$(this).data('remove-thumbnail')){
if($element.find('.IG_DWSTORY_THUMBNAIL').length === 0){
$(this).attr('data-remove-thumbnail', true);
$('.IG_DWSTORY_THUMBNAIL').remove();
logger('(story) Manually removing thumbnail button');
}
else{
$(this).attr('data-remove-thumbnail', true);
logger('(story) Thumbnail button is not present for this picture');
}
}
});
});
// Try to use event listener 'timeupdate' in order to detect if story is a video
//$element.find('video').each(function(){
// $(this).on('timeupdate',function(){
// if(!$(this).data('modify-thumbnail')){
// if($element.find('.IG_DWSTORY_THUMBNAIL').length === 0){
// $(this).attr('data-modify-thumbnail', true);
// onStoryThumbnail(false);
// logger('(story) Manually inserting thumbnail button');
// }
// else{
// $(this).attr('data-modify-thumbnail', true);
// logger('(story) Thumbnail button already inserted');
// }
// }
// });
//});
}
}
}
}