forked from FarisHijazi/SuperGoogleImages
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SuperGoogleImages.user.js
3165 lines (2709 loc) · 119 KB
/
SuperGoogleImages.user.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 Super Google Images
// @namespace https://github.com/FarisHijazi/SuperGoogleImages
// @author Faris Hijazi
// @version 1.2.8
// @description Replace thumbnails with original (full resolution) images on Google images
// @description Ability to download a zip file of all the images on the page
// @description Open google images in page instead of new tab
// @include /^https?://(?:www|encrypted|ipv[46])\.google\.[^/]+/(?:$|[#?]|search|webhp|imgres)/
// @grant GM_xmlhttpRequest
// @grant GM_download
// @grant GM.getValue
// @grant GM.setValue
// @grant GM_setValue
// @grant GM_getValue
// @grant unsafeWindow
// @grant window.close
// @require https://greasyfork.org/scripts/433051-trusted-types-helper/code/Trusted-Types%20Helper.user.js
// @require https://code.jquery.com/jquery-3.4.0.min.js
// @require https://raw.githubusercontent.com/kimmobrunfeldt/progressbar.js/master/dist/progressbar.min.js
// @require https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js
// @require https://github.com/ccampbell/mousetrap/raw/master/mousetrap.min.js
// @require https://rawgit.com/notifyjs/notifyjs/master/dist/notify.js
// @require https://github.com/FarisHijazi/ShowImages.js/raw/master/PProxy.js
// @require https://raw.githubusercontent.com/mitchellmebane/GM_fetch/master/GM_fetch.js
// @require https://github.com/FarisHijazi/GM_downloader/raw/master/GM_Downloader.user.js
// @require https://github.com/FarisHijazi/ShowImages.js/raw/master/ShowImages.js
// @updateUrl https://raw.githubusercontent.com/FarisHijazi/SuperGoogleImages/master/SuperGoogleImages.user.js
// @run-at document-start
// @connect *
// ==/UserScript==
console.log('SuperGoogleImages hi');
// check this:
// https://gist.github.com/bijij/58cc8cfc859331e4cf80210528a7b255/
// https://github.com/FarisHijazi/SuperGoogleImages/projects/1
/**
* Copyright 2019-2030 Faris Hijazi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Metadata object containing info for each image
* @typedef {Object} Meta
* key | description | example values
* @property {string} id: Id - "ZR4fY_inahuKM:",
* @property {string} isu: Hostpage URL - "gifs.cc",
* @property {number} itg: Image Tag - 0,
* @property {string} ity: Image Type - "gif",
*
* @property {number} oh: Original Height - 322,
* @property {string} ou: Original URL - "http://78.media.tumblr.com/....500.gif",
* @property {number} ow: Original Width - 492,
*
* @property {string} rh: Referrer Host - "",
* @property {string} rid: Referrer id - "nyyV1PqBnBltYM",
* @property {number} rmt: Referrer ? ? - 0,
* @property {number} rt: Referrer ? ? - 0,
* @property {string} ru: Referrer URL - "",
*
* @property {string} pt: Primary Title - "",
* @property {string} s: Description - "Photo",
* @property {string} st: Secondary Title - "",
* @property {number} th: Thumbnail Height - 182,
* @property {string} tu: Thumbnail URL - "https://encrypted-tbn0.gstatic.com/images?q",
* @property {number} tw: Thumbnail Width - 278
*
* my added properties:
* @property {string} src: src of the IMG element
* @property {number[]} dim: dimensions [width, height]
*/
/** returns full path, not just partial path */
const normalizeUrl = (function () {
const fakeLink = document.createElement('a');
return function (url) {
fakeLink.href = url;
return fakeLink.href;
};
})();
// main
(function () {
'use strict';
// TODO: replace this with importing GM_dummy_functions, and importing a polyfill
if (typeof unsafeWindow === 'undefined') unsafeWindow = window;
unsafeWindow.unsafeWindow = unsafeWindow;
// prevents duplicate instances
if (typeof unsafeWindow.SuperGoogleImages !== 'undefined')
return;
const SuperGoogleImages = this || {};
unsafeWindow.SuperGoogleImages = SuperGoogleImages;
SuperGoogleImages.$ = $;
// REFACTOR: TODO: group this into an import-able that will do this simply by importing
Set.prototype.addAll = function (range) {
if (range) {
for (const x of range) {
this.add(x);
}
}
return this;
};
Set.prototype.union = function (other) {
if (!other.concat) other = Array.from(other);
return new Set(
other.concat(Array.from(this))
);
};
Set.prototype.intersection = function (other) {
if (!other.filter) other = Array.from(other);
return new Set(
other.filter(x => this.has(x))
);
};
/** this - other
* @param other
* @returns {Set} containing what this has but other doesn't */
Set.prototype.difference = function (other) {
if (!other.has) other = new Set(other);
return new Set(Array.from(this).filter(x => !other.has(x)));
};
function equivalentObjects(a, b) {
if (a == null) {
return b == null;
} else if (b == null) {
return false;
}
const aProps = Object.getOwnPropertyNames(a);
const bProps = Object.getOwnPropertyNames(b);
if (aProps.length !== bProps.length)// If number of properties is different, objects are not equivalent
return false;
for (const propName of aProps) // If values of same property are not equal, objects are not equivalent
if (a[propName] !== b[propName])
return false;
return true;
}
//TODO: move this to UrlUtils
/**
* @return {Object} searchParams as an object
*/
URL.prototype.__defineGetter__('sp', function () {
return Object.fromEntries(this.searchParams.entries());
});
URL.prototype.equals = function (other, hashSensitive = false) {
function equalUrls(url1, url2, hashSensitive = false) {
return (
equivalentObjects(url1.sp, url2.sp) && // equal search params
(url1.hostname === url2.hostname) &&
(!hashSensitive || url1.hash === url2.hash)
);
}
return equalUrls(this, other, hashSensitive);
};
// === end of basic checks and imports ===
const debug = true;
const showImages = new ShowImages({
loadMode: 'parallel',
imagesFilter: (img, anchor) => {
const conditions = [
// !img.classList.contains(showImages.ClassNames.DISPLAY_ORIGINAL),
// !img.closest('.' + this.ClassNames.DISPLAY_ORIGINAL),
// /\.(jpg|jpeg|tiff|png|gif)($|[?&])/i.test(anchor.href),
// !img.classList.contains('irc_mut'),
!img.closest('div.irc_rismo'),
!/^data:/.test(anchor.href),
];
return conditions.reduce((a, b) => a && b);
},
});
showImages.imageManager.loadTimeout = -1;
console.log('SuperGoogleImages showImages:', showImages);
SuperGoogleImages.showImages = showImages;
const pageUrl = new URL(location.href);
const mousetrap = Mousetrap();
SuperGoogleImages.mousetrap = mousetrap;
try {
checkImports(['ProgressBar', '$', 'JSZip'], 'SuperGoogleImages.user.js', true);
console.debug('SuperGoogleImages running');
} catch (error) {
console.error(error);
}
/**
* @type {{
* GMValues: {hideFailedImagesOnLoad: string,},
* ClassNames: {
* buttons: string,
* belowDiv: string
* },
* Selectors: {
* Panel: {
* buttonDropdown: string,
* mainPanel: string,
* panels: string,
* focusedPanel: *,
* ptitle: string,
* panelExitButton: *
* },
* showAllSizes: string,
* selectedSearchMode: string,
* googleButtonsContainer: string,
* sideViewContainer: string,
* searchModeDiv: string,
* searchBox: string
* }
* }}
*/
const Consts = {
GMValues: {
hideFailedImagesOnLoad: 'HIDE_FAILED_IMAGES_ON_LOAD'
},
Selectors: {
imageLinks: 'a[jsname="sTFXNd"]', // includes related images
/** The "All sizes" link from the SearchByImage page*/
showAllSizes: '#jHnbRc > div.O1id0e > span:nth-child(2) > a',
searchModeDiv: 'div.hdtb-mitem',
selectedSearchMode: 'div.hdtb-mitem.hdtb-msel',
searchBox: 'input[type="text"][title="Search"]',
googleButtonsContainer: '#hdtb-msb',
menuItemsAndButtonsContainer: '#hdtb-msb, .tAcEof',
sideViewContainer: '#irc_bg',
/** the panel element containing the current image [data-ved], so if you observe this element, you can get pretty much get all the data you want.*/
Panel: {
//ok, there's a top part, and this top part has 3 panels (only one is shown at a time)
// panelsContainer: '#Sva75c > div > div > div.pxAole'
sidepanelScrollEl: '#irc-ss, #islsp',
mainPanel: 'div#irc_cc, #islsp',
panelExitButton: ['a#irc_cb', 'a#irc_ccbc'].join(),
ptitle: 'div.irc_mmc.i8152 > div.i30053 > div > div.irc_it > span > a.irc_pt.irc_tas.irc-cms.i3598.irc_lth',
buttonDropdown: 'div.irc_mmc.i8152 > div.i30053 > div > div.irc_m.i8164',
focusedPanel: [
'div#irc_cc div.irc_c[style*="translate3d(0px, 0px, 0px)"]', // normal panel mode (old Google)
'#Sva75c > div > div > div.pxAole > div:not([style*="display: none;"])', // for side panel mode
'#Sva75c > div > div > div.pxAole > div:not([aria-hidden=\'true\'])',
].join(),
panels: '#Sva75c > div > div > div.pxAole > div, #irc_cc div.irc_c',
},
},
ClassNames: {
buttons: 'super-button',
belowDiv: 'below-st-div'
}
};
Consts.ClassNames = $.extend(showImages.ClassNames, Consts.ClassNames);
const Components = {
minImgSizeSlider: {},
};
// OPTIONS:
// TODO: add a little dropdown where it'll show you the current options and you can
// modify them and reload the page with your changes
const Preferences = (function () {
const DEFAULTS = {
// everything that has to do with the search page and url
location: {
customUrlArgs: {
// "tbs=isz": "lt",//
// islt: "2mp", // isLargerThan
// tbs: "isz:l", // l=large, m=medium...
// "hl": "en",
},
/**
* @type {string|null}
* if this field is falsy, then there will be no changes to the url.
* disable by prepending with '!'
*/
},
toolbar: {
smallImageSliderDefaultValue: 250,
navbarHideDelay: 700,
},
// these should be under "page"
page: {
staticNavbar: false,
autoLoadMoreImages: false, // somewhat problematic and can be annoying
showImgHoverPeriod: 350, // if negative, then hovering functionality is disabled
},
shortcuts: {
hotkey: 'ctrlKey', // 'altKey', 'shiftKey'
},
loading: {
hideFailedImagesOnLoad: false,
useDdgProxy: true,
},
};
const o = $.extend(DEFAULTS, GM_getValue('Preferences'));
o.store = () => GM_setValue('Preferences', o);
o.get = () => GM_getValue('Preferences');
// write back to storage (in case the storage was empty)
o.store();
return o;
})();
unsafeWindow.Preferences = Preferences;
Preferences.toolbar.navbarHideDelay = 700;
/** TODO: write jsdoc
* @type {{
* elements: {
*
* },
* url: {
* gImgSearchURL,
* reverseImageSearchUrl,
* getGImgReverseSearchURL: function,
* siteSearchUrl: function,
* isOnGoogle,
* isOnGoogleImages,
* isOnGoogleImagesPanel,
* isRightViewLayout
* }
* }}
*/
const GoogleUtils = (function () {
const isOnGoogle = () => GoogleUtils.elements.selectedSearchMode && GoogleUtils.elements.selectedSearchMode.innerHTML === 'Images';
/**
* @type {{
* isOnEncryptedGoogle: boolean,
* googleBaseURL: String,
* gImgSearchURL: String,
* reverseImageSearchUrl: String,
* getGImgReverseSearchURL: Function,
* siteSearchUrl: Function,
* }}
*/
const url = {};
url.isOnEncryptedGoogle = /encrypted.google.com/.test(location.hostname);
url.googleBaseURL = `https://${/google\./.test(location.hostname) ? location.hostname :
((url.isOnEncryptedGoogle ? 'encrypted' : 'www') + '.google.com')}`;
url.gImgSearchURL = `${url.googleBaseURL}/search?&hl=en&tbm=isch&q=`;
url.reverseImageSearchUrl = `${url.googleBaseURL}/searchbyimage?&image_url=`;
url.getGImgReverseSearchURL = _url => _url ? url.reverseImageSearchUrl + encodeURIComponent(_url.trim()) : '';
url.siteSearchUrl = function (query) {
if (query) {
return GoogleUtils.url.gImgSearchURL + 'site:' + encodeURIComponent(query.trim());
}
};
const els = {};
// copy all the selectors from Consts.Selectors and define getters, now you can access `searchModeDiv` by using `elements.searchModeDiv`
// if the selector key ends with 's' (plural), then it gets multiple elements, otherwise just a single element
for (const key of Object.keys(Consts.Selectors)) {
const v = Consts.Selectors[key];
els.__defineGetter__(key, () => key.slice(-1).toLowerCase() === 's' ? // ends with 's'? (is plural?)
document.querySelectorAll(v) : document.querySelector(v)
);
}
const o = {
/** @type{{
* isOnGoogle,
* isOnGoogleImages,
* isOnGoogleImagesPanel,
* isRightViewLayout,
* }}
*/
url: url,
elements: els,
};
o.__defineGetter__('isOnGoogle', isOnGoogle);
o.__defineGetter__('isOnGoogleImages', () =>
new URL(location.href).searchParams.get('tbm') === 'isch' // TODO: find a better way of determining whether the page is a Google Image search
);
o.__defineGetter__('isOnGoogleImagesPanel', () => {
const url1 = new URL(location.href);
return url1.searchParams.has('imgrefurl') && url1.pathname.split('/').pop() === 'imgres';
}
);
o.__defineGetter__('isRightViewLayout', () => { // check if the Google images layout
return !!document.querySelector('#irc_bg.irc-unt, #Sva75c');
}
);
return o;
})();
// unsafeWindow.GoogleUtils = GoogleUtils;
/**
* the zip file
* @type {JSZip}
*/
let zip = new JSZip();
zip.name = (document.title).replace(/site:|( - Google Search)/gi, '');
let shouldShowOriginals = false;
let currentDownloadCount = 0;
let isTryingToClickLastRelImg = false;
const directLinkReplacer = googleDirectLinksInit();
unsafeWindow.directLinkReplacer = directLinkReplacer;
document.cursor = {
pageX: 0,
pageY: 0,
clientX: 0,
clientY: 0,
};
document.addEventListener('mousemove', function (e) {
document.cursor.pageX = e.pageX;
document.cursor.pageY = e.pageY;
document.cursor.clientX = e.clientX;
document.cursor.clientY = e.clientY;
});
/*
* change mouse cursor when hovering over elements for scroll navigation
* cursor found here: https://www.flaticon.com/free-icon/arrows_95103#
*/
const clearEffectsDelayed = (function () {
let timeOut;
return function () {
clearTimeout(timeOut);
timeOut = setTimeout(function () {
clearAllEffects();
// updateQualifiedImagesLabel();
}, 800);
};
})();
if (Preferences.page.autoLoadMoreImages) {
setInterval(function () {
const btn = document.querySelector('#smbw');
if (btn) {
const event = new Event('click');
btn.dispatchEvent(event);
}
}, 1000);
}
processLocation();
elementReady('body').then(onload);
// click showAllSizes link when it appears
if (localStorage.getItem('clickShowAllSizes') === 'true') {
elementReady(Consts.Selectors.showAllSizes).then(function (el) {
localStorage.setItem('clickShowAllSizes', '');
return el.click();
});
}
// === start of function definitions ===
var isFirstMetaUpdate = true; // flag for meta update (first time should be free, next times should have added images)
// called as soon as the "body" is loaded
function onload() {
if (GoogleUtils.isOnGoogleImages || GoogleUtils.isOnGoogleImagesPanel) {
createStyles();
bindKeys();
// wait for searchbar to load
// document.addEventListener('DOMContentLoaded', onContentLoaded);
elementReady(Consts.Selectors.menuItemsAndButtonsContainer).then(onSearchbarLoaded);
// onImageBatchLoaded observe new image boxes that load
observeDocument((mutations, me) => {
// location.href = 'google.com'
// console.log('close()')
// close()
const addedImageBoxes = getImgBoxes(':not(.rg_bx_listed)');
if (!!document.querySelector('#islmp > div > div > div > div') && isFirstMetaUpdate) {
var updateImageMetasRet = updateImageMetas()
if (updateImageMetasRet && updateImageMetasRet.filter(x=>!!x).length) {
isFirstMetaUpdate = false;
}
}
if (!addedImageBoxes.length) {
return;
}
if (!!document.querySelector('#islmp > div > div > div > div')) {
updateImageMetas();
}
if (shouldShowOriginals) {
const thumbnails = [].map.call(getThumbnails(), div => div.closest('img[fullres-src]'))
.filter(img => !!img);
showOriginals(thumbnails);
}
onImageBatchLoaded(addedImageBoxes);
updateDownloadBtnText();
// //Google direct links
// // FIXME: this is what prevents you from opening image tabs
// directLinkReplacer.checkNewNodes(mutations);
}, {
callbackMode: 0,
childList: true,
attributes: true,
// attributeFilter: ['href'],
subtree: true,
});
} else { // else if not google images
if (location.pathname === '/save') {
var imgs = document.querySelectorAll('c-wiz div > div > div > div > div > a > div > div > img');
imgs.forEach(img => {
a = img.closest('a');
var imgurl = new URL(a.href, 'https://' + location.hostname).searchParams.get('imgurl');
if (imgurl) {
img.src = imgurl;
}
});
}
elementReady(() => getElementsByXPath('//a[text()=\'Change to English\']')[0]).then(changeToEnglishAnchors => {
changeToEnglishAnchors.click();
});
}
}
// called when the searchbar is loaded (used for functionality that needs elements to be loaded)
function onSearchbarLoaded() {
// // just deleting the Google home button (cuz it overlaps with the navbar)
// document.querySelector('.qlS7ne').remove();
// binding first letter of each menuItem ([A]ll, [I]mages, [V]ideos, ...)
const menuItems = getMenuItems();
for (const item of Object.keys(menuItems)) {
const callback = function (e) {
const elChild = menuItems[item].firstElementChild;
if (elChild) elChild.click();
};
callback._name = 'Go to [' + item + '] tab';
mousetrap.bind([`shift+${item.charAt(0).toLowerCase()}`], callback);
}
//
// handling safe search and location operations here
//
const ssLink = document.querySelector('#ss-bimodal-strict');
const ussLink = document.querySelector('#ss-bimodal-default');
const safeSearchListener = function (e) {
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
toggle_safesearch();
};
if (ssLink) ssLink.addEventListener('click', safeSearchListener, true);
if (ussLink) ussLink.addEventListener('click', safeSearchListener, true);
// force safe search if already attempted and shouldBeUnsafesearch
if (ussLink && localStorage.getItem('shouldBeUnsafesearch') === 'true') {
console.info('"shouldBeUnsafesearch"=true, but this is not unsafe search, forcing unsafe search using "ipv4"...');
location.assign(unsafeSearchUrl()); // force unsafesearch
localStorage.setItem('shouldBeUnsafesearch', '');
return;
}
const targetHostname = localStorage.getItem('targetHostname');
if (targetHostname && (targetHostname !== location.hostname)) {
localStorage.setItem('targetHostname', '');
location.hostname = targetHostname;
return;
}
injectGoogleButtons()
}
// ============
function bindKeys() {
Mousetrap.addKeycodes({
96: 'numpad0',
97: 'numpad1',
98: 'numpad2',
99: 'numpad3',
100: 'numpad4',
101: 'numpad5',
102: 'numpad6',
103: 'numpad7',
104: 'numpad8',
105: 'numpad9',
107: 'numpad+',
109: 'numpad-',
});
// S S: SafeSearch toggle
mousetrap.bind('s s', toggle_safesearch);
mousetrap.bind(['alt+a', 'a a'], function switchToAnimatedResults() {
console.log('Go to animated');
location.assign(document.querySelector('#TypeAnimated').href);
(
document.querySelector('#TypeAnimated') ||
(document.querySelector('#itp_animated') && document.querySelectoooor('#itp_animated').firstElementChild) ||
document.querySelector('#itp_').firstElementChild ||
document.querySelector('#itp_animated').firstElementChild
).click();
});
mousetrap.bind(['D'], function downloadAll() {
document.querySelector('#downloadBtn').click();
});
// mousetrap.bind(['h'], function toggle_hideFailedImages() {
// document.querySelector('#hideFailedImagesBox').click();
// });
// mousetrap.bind(['g'], function toggle_gifsOnlyCheckbox() {
// document.querySelector('#GIFsOnlyBox').click();
// });
mousetrap.bind(['esc'], removeHash);
mousetrap.bind(['o o'], function displayOriginals() { document.querySelector('#dispOgsBtn').click() });
mousetrap.bind(['/'], function focusSearchbar(e) { // focus search box
const searchBar = document.querySelector(Consts.Selectors.searchBox);
if (!$(searchBar).is(':focus')) {
searchBar.focus();
searchBar.scrollIntoView();
searchBar.select();
searchBar.setSelectionRange(searchBar.value.length, searchBar.value.length);
e.preventDefault();
}
});
// beep
// @info mainImage drop-down panel: #irc_bg
// mousetrap.bind(['ctrl+['], siteSearch_TrimLeft);
// mousetrap.bind(['ctrl+]'], siteSearch_TrimRight);
// mousetrap.bind(['['], function stepDown_minImgSizeSlider(e) {
// Components.minImgSizeSlider.stepDown();
// });
// mousetrap.bind([']'], function stepUp_minImgSizeSlider(e) {
// Components.minImgSizeSlider.stepUp();
// });
// mousetrap.bind(['c'], function goToCollections(e) {
// const btn_ViewSaves = document.querySelector('#ab_ctls > li > a.ab_button');
// console.debug('btn_ViewSaves', btn_ViewSaves);
// if (!!btn_ViewSaves) btn_ViewSaves.click();
// });
document.addEventListener('keydown', e => {
if (e[Preferences.shortcuts.hotkey]) {
const el = document.elementFromPoint(document.cursor.clientX, document.cursor.clientY);
if (!el) return;
const hotkeyEvent = new Event('hotkey');
hotkeyEvent[Preferences.shortcuts.hotkey] = e[Preferences.shortcuts.hotkey];
el.dispatchEvent(hotkeyEvent);
}
});
document.addEventListener('keyup', e => {
if (e[Preferences.shortcuts.hotkey]) {
const el = document.elementFromPoint(document.cursor.clientX, document.cursor.clientY);
if (!el) return;
const hotkeyEvent = new Event('hotkeyup');
hotkeyEvent[Preferences.shortcuts.hotkey] = e[Preferences.shortcuts.hotkey];
el.dispatchEvent(hotkeyEvent);
}
});
console.log('added super google key listener');
}
function toggleShowKeymap(e) {
let keymapTable = document.querySelector('#keymap');
if (keymapTable) {
keymapTable.toggle();
return;
}
//TODO; collapse duplicate keybindings
/** @returns {HTMLDivElement} */
function createKeymapTable(mousetrap = mousetrap) {
function getKeymap(funcNames = false) {
return Object.entries(mousetrap._directMap).map(e => {
return [e[0].slice(0, e[0].lastIndexOf(':')), funcNames ? (e[1]._name || e[1].name) : e[1]]
}).filter(entry => !!entry[1] &&
(String(entry[1]._name || entry[1].name || entry[1]) !== '_callbackAndReset') &&
String(entry[1]._name || entry[1].name || entry[1]).replace(/\s/g, '') !== 'function(){_nextExpectedAction=nextAction;++_sequenceLevels[combo];_resetSequenceTimer();}')
}
const entries = getKeymap();
const $table = $($.parseHTML('<table>'));
// Loop through array and add table cells
for (const row of entries) {
const $row = $($.parseHTML(`<tr>`));
$table.append($row)
for (let cell of row) {
// if not function, then just use the text
if (typeof cell !== 'function') {
const $td = $($.parseHTML(`<td>${cell}</td>`));
$row.append($td);
} else {
// if function: choose the name as the text and use a link that calls the function when clicked
const func = cell;
cell = cell._name || cell.name || '_';
const $td = $($.parseHTML(`<td><a href="javascript:void(0);">${cell}</a></td>`));
$row.append($td);
$td.find('a')[0].addEventListener('click', func);
}
}
}
// ATTACH HTML TO CONTAINER
const container = document.createElement('div');
container.appendChild($table[0]);
return container;
}
// create keymap table
const keymapTableContainer = $('<div style="height: 700px; overflow: auto"></div>');
keymapTable = keymapTableContainer.append($(createKeymapTable(mousetrap)).css({
'left': '30%',
'width': '30%',
'top': '10%',
'z-index': '1002',
'color': 'rgb(255, 255, 255)',
'position': 'fixed',
'text-align': 'center',
'text-shadow': 'rgb(0, 0, 0) 1px 1px 7px',
'font-weight': 'bold',
'background': 'none 0px center repeat scroll rgb(0, 0, 0)',
'overflow': 'hidden',
'border-radius': '10px',
})).attr({
'id': 'keymap'
})[0];
const setKeymapVisibility = function (visible = false) {
if (visible) {
keymapTable.style.display = 'block';
keymapTable.appendChild(keymapTable.styleEl);
keymapTable.invisibleCover.style.display = 'block';
} else { // invisible
keymapTable.style.display = 'none';
keymapTable.styleEl.remove();
keymapTable.invisibleCover.style.display = 'none';
}
};
keymapTable.toggle = () => setKeymapVisibility(keymapTable.style.display === 'none');
// creating the "close" link/button
const closeLink = $('<a href="#" class="close" style="float: right;">Close</a>').on('click', (e) => setKeymapVisibility(false))[0];
keymapTable.firstElementChild.before(closeLink);
// creating blur style (to blur the background)
keymapTable.styleEl = null;
addCss('body > *:not(#keymap) { filter: blur(3px); }', 'keymap-bg-blur').then(el => {
keymapTable.styleEl = el;
keymapTable.appendChild(keymapTable.styleEl);
});
// creating invisible cover (click listener for exiting)
keymapTable.invisibleCover = $('<div>').css({
'position': 'fixed',
'padding': '0px',
'margin': '0px',
'top': '0px',
'left': '0px',
'width': '100%',
'height': '100%',
'background': 'rgba(255, 255, 255, 0.5)',
}).on('click', (e) => setKeymapVisibility(false))[0];
Mousetrap.bind('escape', (e) => setKeymapVisibility(false));
document.body.appendChild(keymapTable);
keymapTable.after(keymapTable.invisibleCover);
}
// return true when there will be a change
function processLocation() {
// URL args: Modifying the URL and adding arguments, such as specifying the size
if (Preferences.location.customUrlArgs && Object.keys(Preferences.location.customUrlArgs).length) {
for (const key in Preferences.location.customUrlArgs) {
if (Preferences.location.customUrlArgs.hasOwnProperty(key)) {
if (pageUrl.searchParams.has(key))
pageUrl.searchParams.set(key, Preferences.location.customUrlArgs[key]);
else {
pageUrl.searchParams.append(key, Preferences.location.customUrlArgs[key]);
}
}
}
console.debug('new location:', pageUrl.toString());
}
if (!new URL(location.href).equals(pageUrl)) {
location.assign(pageUrl.toString());
return true;
}
}
/**
* Checks that the `window` object contains the properties in `importNames`
* @param {Array} importNames
* @param {String} scriptName
* @param {Boolean} stopExecution if there are missing
*/
function checkImports(importNames = [], scriptName = '', stopExecution = false) {
const missing = [];
for (const importName of importNames.filter(i => !!i)) {
if (!window.hasOwnProperty(importName)) {
console.error(
'[' + scriptName + '] script has a is missing an import:', importName,
'\nPlease make sure that it is included in the "//@require" field in the userscript metadata block'
);
missing.push(importName);
}
}
if (missing.length !== 0 && stopExecution) {
console.error('Stopping execution due to missing imports:', missing);
void (0);
throw new Error('Stopping execution due to missing imports:\n' + missing.join('\n- '));
}
return missing;
}
/**
* is el1 == el2 OR contains el2?
* @param element
* @param el2
* @return {boolean}
*/
function isOrContains(element, el2) {
if (element === el2) console.debug('element == el2', element, el2);
return element.contains(el2) || element === el2;
}
function getImgMetaById(id) {
if (id === '') return false;
for (const metaEl of document.querySelectorAll('div.rg_meta')) {
if (metaEl.innerText.indexOf(id) > -1) {
try {
return JSON.parse(metaEl.innerText);
} catch (e) {
console.warn('getImgMetaById():', e);
return false;
}
}
}
return false;
}
/**
* @param {string} torrentName
* @param {string} torrentPageURL
* @returns {string}
* https://rarbgaccess.org/download.php?id= kmvf126 &f= <TorrentName>-[rarbg.to].torrent
*/
function extractRarbgTorrentURL(torrentName, torrentPageURL) {
const torrentURL = torrentPageURL.replace(/torrent\//i, 'download.php?id=') + '&f=' + torrentName.split(/\s+/)[0];
console.debug('extracted rarbg torrent URL:', torrentURL);
return torrentURL;
}
/** @param visibleOnly {boolean}: optional: set to true to exclude thumbnails that aren't visible
* @returns {HTMLImageElement[]} */
function getThumbnails(visibleOnly = false) {
// language=CSS
const selector = ['div.rg_bx', 'div > a[jsname] img.rg_i'].join();
if (visibleOnly) {
return [].filter.call(document.querySelectorAll(selector), e => !/(:none;)|(hidden)/.test(e.style.display));
}
return Array.from(document.querySelectorAll(selector));
}
function updateQualifiedImagesLabel(value = 0) {
//FIXME: this is a waste of resources, we're only using the length
if (!value) value = getQualifiedGImgs({}).length;
const satCondLabel = document.querySelector('#satCondLabel');
if (satCondLabel)
satCondLabel.innerHTML = value + ' images satisfying conditions';
const dlLimitSlider = document.querySelector('#dlLimitSlider');
if (dlLimitSlider && dlLimitSlider.value < value) {
dlLimitSlider.value = value;
document.querySelector('#dlLimitSliderValue').innerText = value;
}
}
function highlightSelection() {
const sliderValueDlLimit = this.value;
document.querySelector('#dlLimitSliderValue').innerHTML = sliderValueDlLimit;
// Highlighting images that will be downloaded
let i = 0;
for (const img of getImgBoxes(' img')) {
if (i <= sliderValueDlLimit && img.classList.contains('qualified-dimensions')) {
img.classList.add('drop-shadow', 'out');
img.classList.remove('in');
i++;
} else {
img.classList.remove('out');
img.classList.add('blur', 'in');
}
}
updateQualifiedImagesLabel();
}
// TODO: use jquery to create the elements, it'll be much cleaner
/**Modify the navbar and add custom buttons
* @returns {Promise<Element>} the navbarContentDiv
*/
function injectGoogleButtons() {
console.log('injectGoogleButtons()');
const controlsContainer = createElement('<div id="google-controls-container"</div>');
/*q('#abar_button_opt').parentNode*/ //The "Settings" button in the google images page
const menuItemsAndButtonsContainer = document.querySelector(Consts.Selectors.menuItemsAndButtonsContainer);
// auto-click on "tools" if on Google Images @google-specific
const toolsButton = menuItemsAndButtonsContainer.querySelector('.hdtb-tl, div.PAYrJc > div.ssfWCe');
if (!!toolsButton) {
if (!toolsButton.classList.contains('hdtb-tl-sel')) { // if the tools bar is not already visible (not already clicked)
toolsButton.click();
} else console.warn('tools button already activated');
} else console.warn('tools button not found');
// buttons
const createGButton = (id, innerText, onClick) => {
const button = createElement(`<button class="${Consts.ClassNames.buttons} sg sbtn hdtb-tl" id="${id}">${innerText.replace(/\s/g, ' ')}</button>`);
if (typeof (onClick) === 'function') {
button.onclick = function () {
onClick();
};
}
return button;
};
/**
* @param {string} id the checkbox element id
* @param {string=} labelText
* @param {Function=} onChange on box change, Function(checked: bool) this: checkboxEl
* @param {boolean=} checked
* @returns {HTMLDivElement} this label element contains a checkbox input element
*/
const createGCheckBox = (id, labelText = 'label', onChange = () => null, checked = false) => {
checked = GM_getValue(id, checked); // load value, fallback to passed value
const $container = $('<div>').attr({
'id': id.trim() + '-div',
'class': 'sg',
}).css({
'display': 'inline',
});
const $checkbox = $('<input>').attr({