forked from Amazon-Vine-Explorer/AmazonVineExplorer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVineExplorer.user.js
2721 lines (2305 loc) · 115 KB
/
VineExplorer.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 Amazon Vine Explorer
// @namespace http://tampermonkey.net/
// @version 0.10.9.0.1
// @updateURL https://raw.githubusercontent.com/Amazon-Vine-Explorer/AmazonVineExplorer/main/VineExplorer.user.js
// @downloadURL https://raw.githubusercontent.com/Amazon-Vine-Explorer/AmazonVineExplorer/main/VineExplorer.user.js
// @description Better View, Search and Explore for Amazon Vine Products - Vine Voices Edition
// @author MarkusSR1984, Christof121
// @match *://www.amazon.de/*
// @match *://www.amazon.com/*
// @match *://www.amazon.co.uk/*
// @license MIT
// @icon https://raw.githubusercontent.com/Amazon-Vine-Explorer/AmazonVineExplorer/main/vine_logo.png
// @run-at document-start
// @grant GM_getValue
// @grant GM_setValue
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.xmlHttpRequest
// @grant unsafeWindow
// @require https://raw.githubusercontent.com/Amazon-Vine-Explorer/AmazonVineExplorer/main/globals.js
// @require https://raw.githubusercontent.com/Amazon-Vine-Explorer/AmazonVineExplorer/main/class_db_handler.js
// @require https://raw.githubusercontent.com/Amazon-Vine-Explorer/AmazonVineExplorer/main/class_product.js
// External Source
// @require https://raw.githubusercontent.com/eligrey/FileSaver.js/v2.0.4/src/FileSaver.js
// @require https://raw.githubusercontent.com/Christof121/VineFetchFix/main/fetchfix.js
// ==/UserScript==
/*
Versioning:
a.b.c[.d]
a => Hauptversion(Major), ändert sich nur bei breaking oder anderen gravirenden änderungen. Solle In diesem Fall also die 1 nie überschreiten.
b => Feature(Minor), ändert sich nur wenn neue Features hinzukommen oder gößere umstellungen im Hintergrund passiert sind
c => Patch, kleinere Änderungen oder "größere" Bugfixes
d => Micro(OPTIONAL), kleine Bugfixes die nur wenige Zeilen Code beinhalten. Wird normalerweise nicht an die Versionnummer angehängt und nur in ausnahmefällen verwendet. Wie z.B. 0.6.4.1 - Das war nur eine Fehlerhafte Variablendeklaration. musste aber public gehen weil es ein Breaking Bug war
Sammlung der Ideen:
- Pageination nach oben schieben || Kopieren
- Tooltipp mit der langen Beschreibung auf der kurzen
- Bestellte Produkte mit Tag versehen ?
- Automatisches Bestellen via Prioliste ?!?
Todo:
- Reload der Neue Produkte Seite nach einem Click auf "Alle als gesehen Markieren"
- Originale Pagination auf den eigenen Seiten verstecken
*/
'use strict';
console.log(`Init Vine Voices Explorer ${AVE_VERSION}`);
/**
* On witch page are we atm ? PAGETYPE
* @type {PAGETYPE}
*/
let currentMainPage;
loadSettings();
fastStyleChanges();
let searchInputTimeout;
let backGroundScanTimeout;
let TimeouteScrollTilesBufferArray = [];
let BackGroundScanIsRunning = false;
// Make some things accessable from console
unsafeWindow.ave = {
classes: [
DB_HANDLER = DB_HANDLER
],
config: SETTINGS,
event: ave_eventhandler,
};
const database = new DB_HANDLER(DATABASE_NAME, DATABASE_OBJECT_STORE_NAME, DATABASE_VERSION, (res, err) => {
if (err) {
console.error(`Somithing was going wrong while init database :'(`);
return;
} else {
let _execLock = false;
console.log('Lets Check where we are....');
if (SITE_IS_VINE){
console.log('We are on Amazon Vine'); // We are on the amazon vine site
if(SETTINGS.DarkMode){
waitForHtmlElmement('body', () => {
injectDarkMode();
})
}
const urlParams = new URLSearchParams(window.location.search);
const aveData = urlParams.get('vine-data');
let aveShareData = localStorage.getItem('ave-share-details');
if(aveData || aveShareData){
let _data = aveShareData ? JSON.parse(aveShareData) : (aveData ? JSON.parse(aveData) : null);
waitForHtmlElmement('body', () => {
let aveShareElementTmp = document.createElement('div');
aveShareElementTmp.style.display = "none";
aveShareElementTmp.innerHTML = `
<span class="a-button a-button-primary vvp-details-btn" id="a-autoid-0">
<span class="a-button-inner">
<input data-asin="${_data.asin}" data-is-parent-asin="${_data.isParentAsin}" data-recommendation-id="${_data.recommendationId}" data-recommendation-type="VENDOR_TARGETED" class="a-button-input" type="submit" aria-labelledby="a-autoid-0-announce">
<span class="a-button-text" aria-hidden="true" id="a-autoid-0-announce">Weitere Details
</span>
</span>
</span>
`;
document.body.appendChild(aveShareElementTmp);
// Warte auf das nächste Ereigniszyklus, um sicherzustellen, dass das Element vollständig gerendert wurde
setTimeout(() => {
aveShareElementTmp.querySelector('input').click();
setTimeout(() => {
//aveShareElementTmp.remove();
localStorage.removeItem('ave-share-details');
}, 200);
}, 500);
})
//https://www.amazon.de/vine/api/recommendations/A1PA6795UKMFR9%23B0CW9Q5N53%23vine.enrollment.41aad59f-9ff3-49c4-a3e1-d3f3c43c2536/item/B0CW9Q5N53?imageSize=180
}
addAveSettingsTab();
addAVESettingsMenu();
waitForHtmlElmement('.vvp-details-btn', () => {
if (_execLock) return;
_execLock = true;
addBranding();
detectCurrentPageType();
let _tileCount = 0;
const _initialWaitForAllTiles = setInterval(() => {
const _count = document.getElementsByClassName('vvp-details-btn').length // Buttons take a bit more time as tiles
if (_count > _tileCount) {
_tileCount = _count;
} else {
clearInterval(_initialWaitForAllTiles);
init(true);
}
}, 100);
});
waitForHtmlElmement('.vvp-no-offers-msg', () => { // Empty Page ?!?!
if (_execLock) return;
_execLock = true;
if(SETTINGS.DarkMode){
waitForHtmlElmement('body', () => {
injectDarkMode();
})
}
addBranding();
init(false);
});
} else if (SITE_IS_SHOPPING) {
console.log('We are on Amazon Shopping'); // We are on normal amazon shopping - maybe i hve forgotten any other site then we have to add it as not here
_execLock = true;
waitForHtmlElmement('body', () => {
addBranding(); // For now, olny show that the script is active
});
useEnrollmentData() // Function to use enrollment data from URL
function useEnrollmentData() {
const urlParams = new URLSearchParams(window.location.search);
const aveData = urlParams.get('vine-data');
if (aveData) {
const enrollmentData = JSON.parse(decodeURIComponent(aveData));
//Redirect to Vine and Open Item
localStorage.setItem('ave-share-details', JSON.stringify(enrollmentData));
window.open(`${window.location.origin}/vine/vine-items`, '_blank');
}
}
}
}
});
unsafeWindow.ave.database = database;
let oldCountOfNewItems = 0;
let showDbUpdateLogoTimeout = null;
let showDbUpdateLogoIcon = null;
ave_eventhandler.on('ave-database-changed', () => {
console.warn('EVENT - Database has new Data for us! we should look what has changed');
updateNewProductsBtn();
if (showDbUpdateLogoTimeout) clearTimeout(showDbUpdateLogoTimeout);
if (!showDbUpdateLogoIcon) showDbUpdateLogoIcon = addDBLoadingSymbol();
showDbUpdateLogoTimeout = setTimeout(() => {
if (showDbUpdateLogoIcon) showDbUpdateLogoIcon.remove();
showDbUpdateLogoTimeout = null;
showDbUpdateLogoIcon = null;
}, 5000);
})
window.onscroll = () => { // ONSCROLL Event handler
stickElementToTopScrollEVhandler('ave-btn-allseen', '5px');
stickElementToTopScrollEVhandler('ave-btn-db-allseen', '40px');
stickElementToTopScrollEVhandler('ave-btn-backtotop', '75px');
if (currentMainPage == PAGETYPE.ALL) handleInfiniteScroll();
};
let blockHandleInfiniteScroll = false;
let infiniteScrollLastPreloadedPage = 1;
let infiniteScrollMaxPreloadPage = 125; // Hardcoded for scrolltest, must lated get extracted from Pagination
let inifiniteScrollBlockAppend = false;
let infiniteScrollTilesBufferArray = [];
function injectDarkMode() {
const _darkModeIgnoreBackgroundColor = `
i,
span.a-declarative *,
#navbar-main *,
#ave-btn-allseen *,
#ave-btn-db-allseen *,
#ave-btn-backtotop *,
#ave-branding-text,
#ave-brandig-text,
.animated-progress *,
.a-switch.a-declarative,
.vvp-reviews-table--actions-col *,
.a-tab-heading,
.a-tab-heading a,
.ave-favorite-star,
.vvp-item-tile,
.vvp-item-tile-content,
.vvp-item-tile-content *,
.a-popover-lgtbox,
.a-modal-scroller.a-declarative,
#ave-btn-favorites *,
#ave-btn-list-new *,
.ave-settings-label-switch *,
.a-last *
`
const _darkModeIgnoreColor = `
span.a-declarative *,
#navbar-main *,
#ave-btn-allseen *,
#ave-btn-db-allseen *,
#ave-btn-backtotop *,
#ave-branding-text,
#ave-brandig-text,
.a-switch.a-declarative,
.vvp-reviews-table--actions-col *,
.vvp-details-btn *,
.vvp-header-link *,
.a-link-normal,
#ave-btn-favorites *,
#ave-btn-list-new *,
.a-last *
`
const _darkModeIgnoreIcons = `
#vvp-feedback-star-rating
`
const darkCSS = `
:root{
--primary-color: ${SETTINGS.DarkModeColor};
--secondary-color: ${SETTINGS.DarkModeBackgroundColor};
}
.ave-color, .ave-color *:not(${_darkModeIgnoreColor}){
color: var(--primary-color) !important;
}
.ave-background-color, .ave-background-color *:not(${_darkModeIgnoreBackgroundColor}){
background-color: var(--secondary-color) !important;
}
.a-expander-content-fade,
.a-popover-footer::before,
.a-popover-wrapper::after
{
background: none !important;
}
i:not(${_darkModeIgnoreIcons}){
background-color: transparent !important;
filter: invert(1) !important;
}
`
// Erstelle ein neues Style-Element
var styleElement = document.createElement('style');
styleElement.type = 'text/css';
// Füge die CSS-Variable und den Wert am Anfang des Style-Elements hinzu
styleElement.textContent = darkCSS;
// Füge das Style-Element am Anfang des <head>-Tags hinzu
document.head.insertBefore(styleElement, document.head.firstChild);
document.body.classList.add('ave-color','ave-background-color');
}
function handleInfiniteScroll() {
console.log('Called handleInfiniteScroll()');
if (!inifiniteScrollBlockAppend) {
inifiniteScrollBlockAppend = true;
// setTimeout(async ()=> {},10);
appendInfiniteScrollTiles(()=>{inifiniteScrollBlockAppend = false;})
}
if (SETTINGS.EnableInfiniteScrollLiveQuerry) {
if (blockHandleInfiniteScroll) return;
blockHandleInfiniteScroll = true;
const _maxScrollHeight = Math.max(document.body.scrollHeight - window.innerHeight, document.documentElement.scrollHeight - window.innerHeight);
console.log(`handleInfiniteScroll(): _maxScrollHeight: ${_maxScrollHeight} window.scrollY+inner: ${window.scrollY + window.innerHeight}`);
if (_maxScrollHeight > (window.scrollY + (window.innerHeight * 2))){
blockHandleInfiniteScroll = false;
return;
} else if (infiniteScrollTilesBufferArray.length < 1000 && infiniteScrollLastPreloadedPage < infiniteScrollMaxPreloadPage) {
const _baseUrl = (/(http[s]{0,1}\:\/\/[w]{0,3}.amazon.[a-z]{1,}.{0,1}[a-z]{0,}\/vine\/vine-items)/.exec(window.location.href))[1];
infiniteScrollLastPreloadedPage++;
getTilesFromURL(`${_baseUrl}?queue=encore&pn=&cn=&page=${infiniteScrollLastPreloadedPage}`, (tiles) =>{
infiniteScrollTilesBufferArray = infiniteScrollTilesBufferArray.concat(tiles);
blockHandleInfiniteScroll = false;
if (infiniteScrollTilesBufferArray.length < 500) handleInfiniteScroll();
});
} else {
blockHandleInfiniteScroll = false;
}
}
}
function getUrlParameter(name) {
const _queryString = window.location.search;
const _urlParams = new URLSearchParams(_queryString);
return _urlParams.get(name);
}
function detectCurrentPageType(){
if (/http[s]{0,1}\:\/\/[w]{0,3}.amazon.[a-z]{1,}.{0,1}[a-z]{0,}\/vine\/vine-items$/.test(window.location.href)) {
currentMainPage = PAGETYPE.ORIGINAL_LAST_CHANCE;
} else if (getUrlParameter('queue') == 'last_chance') {
currentMainPage = PAGETYPE.ORIGINAL_LAST_CHANCE;
} else if (getUrlParameter('queue') == 'potluck') {
currentMainPage = PAGETYPE.OROGINAL_POTLUCK;
} else if (getUrlParameter('queue') == 'encore') {
currentMainPage = PAGETYPE.ORIGINAL_SELLER;
}
// alert(`currentMainPage is: ${currentMainPage}`);
// getUrlParameter('ave-subpage');
}
async function parseTileData(tile) {
return new Promise((resolve, reject) => {
if (SETTINGS.DebugLevel > 5) console.log(`Called parseTileData(`, tile, ')');
const _id = tile.getAttribute('data-recommendation-id');
database.get(_id).then((_ret) => {
if (_ret) {
_ret.gotFromDB = true;
_ret.ts_lastSeen = unixTimeStamp();
if (SETTINGS.DebugLevel > 14) console.log(`parseTileData(): got DB Entry`);
database.update(_ret);
resolve(_ret);
} else {
//We have to wait for a lot of Stuff
waitForHtmlElmement('.vvp-item-tile-content',async () => {
const _div_vpp_item_tile_content = tile.getElementsByClassName('vvp-item-tile-content')[0];
if (SETTINGS.DebugLevel > 14) console.log(`parseTileData(): wait 1`);
waitForHtmlElmement('img', async () => {
const _div_vpp_item_tile_content_img = _div_vpp_item_tile_content.getElementsByTagName('img')[0];
if (SETTINGS.DebugLevel > 14) console.log(`parseTileData(): wait 2`);
waitForHtmlElmement('.vvp-item-product-title-container', async () => {
const _div_vvp_item_product_title_container = _div_vpp_item_tile_content.getElementsByClassName('vvp-item-product-title-container')[0];
if (SETTINGS.DebugLevel > 14) console.log(`parseTileData(): wait 3`);
waitForHtmlElmement('a', async () => {
const _div_vvp_item_product_title_container_a = _div_vvp_item_product_title_container.getElementsByTagName('a')[0];
if (SETTINGS.DebugLevel > 14) console.log(`parseTileData(): wait 4`);
waitForHtmlElmement('.a-button-inner', async () => {
const _div_vpp_item_tile_content_button_inner = _div_vpp_item_tile_content.getElementsByClassName('a-button-inner')[0];
if (SETTINGS.DebugLevel > 14) console.log(`parseTileData(): wait 5`);
waitForHtmlElmement('input', async () => {
const _div_vpp_item_tile_content_button_inner_input = _div_vpp_item_tile_content_button_inner.getElementsByTagName('input')[0];
if (SETTINGS.DebugLevel > 14) console.log(`parseTileData(): wait 6`);
const _newProduct = new Product(_id);
_newProduct.data_recommendation_id = _id;
_newProduct.data_img_url = tile.getAttribute('data-img-url');
_newProduct.data_img_alt = _div_vpp_item_tile_content_img.getAttribute('alt') || "";
_newProduct.link = _div_vvp_item_product_title_container_a.getAttribute('href');
_newProduct.description_full = _div_vvp_item_product_title_container_a.getElementsByClassName('a-truncate-full')[0].textContent;
_newProduct.data_asin = _div_vpp_item_tile_content_button_inner_input.getAttribute('data-asin');
_newProduct.data_recommendation_type = _div_vpp_item_tile_content_button_inner_input.getAttribute('data-recommendation-type');
_newProduct.data_asin_is_parent = (_div_vpp_item_tile_content_button_inner_input.getAttribute('data-is-parent-asin') == 'true');
_newProduct.description_short = _div_vvp_item_product_title_container_a.getElementsByClassName('a-truncate-cut')[0].textContent;
if (_newProduct.description_short == '') {
if (SETTINGS.DebugLevel > 14) console.log(`parseTileData(): we don´t have a shot description`);
let _timeLoopCounter = 0;
const _maxLoops = Math.round(SETTINGS.FetchRetryMaxTime / SETTINGS.FetchRetryTime);
const _halfdelay = (SETTINGS.FetchRetryTime / 2)
function timeLoop() {
if (_timeLoopCounter++ < _maxLoops){
setTimeout(() => {
const _short = _div_vvp_item_product_title_container_a.getElementsByClassName('a-truncate-cut')[0].textContent;
if (_short != ""){
_newProduct.description_short = _short;
resolve(_newProduct);
} else {
timeLoop();
}
}, _halfdelay + Math.round(Math.random() * _halfdelay * 2));
} else {
_newProduct.description_short = `${_newProduct.description_full.substr(0,50)}...`;
_newProduct.generated_short = true;
resolve(_newProduct);
}
}
timeLoop();
} else {
if (SETTINGS.DebugLevel > 14) console.log(`parseTileData(): END`);
resolve(_newProduct);
}
// if (SETTINGS.DebugLevel > 10) console.log(`parseTileData(${tile}) RETURNS :: ${JSON.stringify(_newProduct, null, 4)}`);
}, _div_vpp_item_tile_content_button_inner)
}, _div_vpp_item_tile_content)
}, _div_vvp_item_product_title_container)
}, _div_vpp_item_tile_content);
}, _div_vpp_item_tile_content);
}, tile)
}
});
})
}
function reloadPageWithSubpageTarget(target) {
if (window.location.href.includes('?')) {
window.location.href = window.location.href + `&ave-subpage=${target}`;
} else {
window.location.href = window.location.href + `?ave-subpage=${target}`;
}
}
function addLeftSideButtons(forceClean) {
const _nodesContainer = document.getElementById('vvp-browse-nodes-container');
if (forceClean) _nodesContainer.innerHTML = '';
_nodesContainer.appendChild(document.createElement('p')); // A bit of Space above our Buttons
const _setAllSeenBtn = createButton('Aktuelle Seite als gesehen markieren','ave-btn-allseen', `width: 240px; background-color: ${SETTINGS.BtnColorMarkCurrSiteAsSeen};`, () => {
if (SETTINGS.DebugLevel > 10) console.log('Clicked All Seen Button');
markAllCurrentSiteProductsAsSeen();
});
const _setAllSeenDBBtn = createButton('Alle als gesehen markieren','ave-btn-db-allseen', `left: 0; width: 240px; background-color: ${SETTINGS.BtnColorMarkAllAsSeen};`, () => {
if (SETTINGS.DebugLevel > 10) console.log('Clicked All Seen Button');
setTimeout(() => {
database.getAll().then((prodsArr) => {
const _prodsArryLength = prodsArr.length;
for (let i = 0; i < _prodsArryLength; i++) {
const _currProd = prodsArr[i];
_currProd.isNew = false;
database.update(_currProd);
}
})
}, 30);
});
const _backToTopBtn = createButton('Zum Seitenanfang','ave-btn-backtotop', `width: 240px; background-color: ${SETTINGS.BtnColorBackToTop};`, () => {
if (SETTINGS.DebugLevel > 10) console.log('Clicked back to Top Button');
window.scrollTo(0, 0);
});
_nodesContainer.appendChild(_setAllSeenBtn);
_nodesContainer.appendChild(_setAllSeenDBBtn);
_nodesContainer.appendChild(_backToTopBtn);
// const _clearDBBtn = createButton('Datenbank Bereinigen', 'background-color: orange;', () => {
// if (SETTINGS.DebugLevel > 10) console.log('Clicked clear DB Button');
// cleanUpDatabase();
// });
// _nodesContainer.appendChild(_clearDBBtn);
}
function markAllCurrentSiteProductsAsSeen(cb = () => {}) {
const _tiles = document.getElementsByClassName('vvp-item-tile');
const _tilesLength = _tiles.length;
let _returned = 0;
for (let i = 0; i < _tilesLength; i++) {
const _tile = _tiles[i];
const _id = _tile.getAttribute('data-recommendation-id');
database.get(_id).then((prod) => {
prod.isNew = false;
database.update(prod).then( () => {
updateTileStyle(prod);
_returned++;
if (_returned == _tilesLength) cb();
})
})
}
}
function markAllCurrentDatabaseProductsAsSeen(cb = () => {}) {
if (SETTINGS.DebugLevel > 10) console.log('Called markAllCurrentDatabaseProductsAsSeen()');
database.getNewEntries().then((prods) => {
const _prodsLength = prods.length;
let _returned = 0;
if (SETTINGS.DebugLevel > 10) console.log(`markAllCurrentDatabaseProductsAsSeen() - Got ${_prodsLength} Products with Tag isNew`);
if (_prodsLength == 0) {
cb(true);
return;
}
for (let i = 0; i < _prodsLength; i++) {
const _currProd = prods[i];
_currProd.isNew = false;
database.update(_currProd, ()=> {
if (SETTINGS.DebugLevel > 10) console.log(`markAllCurrentDatabaseProductsAsSeen() - Updated ${_currProd.id}`);
_returned++
if (_returned == _prodsLength) cb(true);
})
}
});
}
function createButton(text, id, style, clickHandler){
const _btnSpan = document.createElement('span');
_btnSpan.setAttribute('id', id);
_btnSpan.setAttribute('class', 'a-button a-button-normal a-button-toggle');
_btnSpan.setAttribute('aria-checked', 'true');
_btnSpan.style.marginLeft = '0';
_btnSpan.style.marginTop = '5px';
_btnSpan.innerHTML = `
<span class="a-button-inner" style="${style || ''}">
<span class="a-button-text">${text}</span>
</span>
`;
_btnSpan.addEventListener('click', (ev) => {
if (clickHandler) {
clickHandler(ev);
} else {
alert('\r\nHier gibt es nix zu sehen.\r\nZumindest noch nicht :P');
}
});
return _btnSpan;
}
async function createTileFromProduct(product, btnID, cb) {
if (!product && SETTINGS.DebugLevel > 10) console.error(`createTileFromProduct got no valid product element`);
return new Promise((resolve, reject) => {
const _btnAutoID = btnID || Math.round(Math.random() * 10000);
const _tile = document.createElement('div');
_tile.setAttribute('class', 'vvp-item-tile');
_tile.setAttribute('data-recommendation-id', product.data_recommendation_id);
_tile.setAttribute('data-img-url', product.data_img_url);
_tile.setAttribute('style', (product.notSeenCounter > 0) ? SETTINGS.CssProductRemovalTag : (product.isFav) ? SETTINGS.CssProductNewTag : (product.isNew) ? SETTINGS.CssProductNewTag : SETTINGS.CssProductDefault);
_tile.innerHTML =`
<div class="vvp-item-tile-content">
<img alt="${product.data_img_alt}" src="${product.data_img_url}">
<div class="vvp-item-product-title-container">
<a class="a-link-normal" target="_blank" rel="noopener" href="${product.link}">
<span class="a-truncate" data-a-word-break="normal" data-a-max-rows="2" data-a-overflow-marker="&hellip;" style="line-height: 1.3em !important; max-height: 2.6em;" data-a-recalculate="false" data-a-updated="true">
<span class="a-truncate-full a-offscreen">${product.description_full}</span>
<span class="a-truncate-cut" aria-hidden="true" style="height: 2.6em;">${product.description_short}</span>
</span>
</a>
</div>
<span class="a-button a-button-primary vvp-details-btn" id="a-autoid-${_btnAutoID}">
<span class="a-button-inner">
<input data-asin="${product.data_asin}" data-is-parent-asin="${product.data_asin_is_parent}" data-recommendation-id="${product.data_recommendation_id}" data-recommendation-type="${product.data_recommendation_type}" class="a-button-input" type="submit" aria-labelledby="a-autoid-${_btnAutoID}-announce">
<span class="a-button-text" aria-hidden="true" id="a-autoid-${_btnAutoID}-announce">Weitere Details</span>
</span>
</span>
</div>
`;
_tile.prepend(createFavStarElement(product, btnID));
_tile.prepend(createShareElement(product, btnID));
waitForHtmlElmement('.vvp-item-product-title-container', (_elem) => {
insertHtmlElementAfter(_elem, createTaxInfoElement(product, btnID));
}, _tile)
// insertHtmlElementAfter((_tile.getElementsByClassName('vvp-item-product-title-container')[0]), createTaxInfoElement(product, btnID));
if (cb) cb(_tile);
resolve(_tile);
})
}
function createFavStarElement(prod, index = Math.round(Math.random()* 10000)) {
const _favElement = document.createElement('div');
_favElement.setAttribute("id", `p-fav-${index || Math.round(Math.random() * 5000)}`);
_favElement.classList.add('ave-favorite-star');
_favElement.style.cssText = SETTINGS.CssProductFavStar();
_favElement.textContent = '★';
if (prod.isFav) _favElement.style.color = SETTINGS.FavStarColorChecked; // SETTINGS.FavStarColorChecked = Gelb;
return _favElement;
}
function createShareElement(prod, index = Math.round(Math.random()* 10000)) {
const _shareElement = document.createElement('div');
_shareElement.setAttribute("id", `ave-p-share-${index || Math.round(Math.random() * 5000)}`);
_shareElement.classList.add('ave-share');
_shareElement.textContent = '🔗';
_shareElement.style.float = 'left';
_shareElement.style.display = 'flex';
_shareElement.style.margin = '0';
_shareElement.style.cursor = 'pointer';
return _shareElement;
}
let run = 0;
function shareEventHandlerClick(event, _data){
if(_data.recommendation_id){
console.log("[AVE]",_data);
const newUrl = `${window.location.origin}/dp/${_data.asin}?vine-data=${encodeURIComponent(JSON.stringify({
asin: _data.asin,
isParentAsin: _data.parent_asin,
recommendationId: _data.recommendation_id,
tax: _data.tax,
}))}`;
const urlParams = new URLSearchParams(window.location.search);
let queueParam = currentMainPage;
//let queueParam = urlParams.get('queue');
let pageParam = urlParams.get('page');
if(pageParam == null){pageParam = 1}
let page = ""
switch(queueParam){
case PAGETYPE.OROGINAL_POTLUCK:
queueParam = "Mein FSE"
page = `Seite: ${pageParam}`
break;
case PAGETYPE.ORIGINAL_LAST_CHANCE:
queueParam = "Verfügbar für Alle"
page = `Seite: ${pageParam}`
break;
case PAGETYPE.ORIGINAL_SELLER:
queueParam = "Zusätzliche Artikel"
page = `Seite: ${pageParam}`
break;
default:
queueParam = ""
page = ``
break;
}
let shareText = `
${queueParam}
${page}
${_data.tax}
${newUrl}`
const cursorPosition = event.target.selectionStart;
const inputRect = event.target.getBoundingClientRect();
const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
const scrollY = window.pageYOffset || document.documentElement.scrollTop;
let avePopup = document.createElement('div');
avePopup.style.position = 'absolute';
avePopup.style.zIndex = '9999';
avePopup.style.padding = '5px'
avePopup.style.top = `${inputRect.top + scrollY}px`;
avePopup.style.left = `${inputRect.left + scrollX}px`;
avePopup.style.border = '5px solid black';
avePopup.style.borderRadius = '100vh';
avePopup.style.backgroundColor = 'white'
avePopup.style.transform = 'translate(-50%, -100%)'
avePopup.style.opacity = '0';
avePopup.style.transition = "opacity 0.2s ease-in-out";
navigator.clipboard.writeText(shareText).then(() => {
avePopup.innerText = "Text wurde in die Zwischenablage kopiert."
}).catch(err => {
avePopup.innerText = `Fehler beim Kopieren in die Zwischenablage: ${err}`
});
document.body.appendChild(avePopup);
// Timeout 0ms for the next Event Cycle -> Give time to render
setTimeout(()=> {
avePopup.style.opacity = '1';
}, 0);
setTimeout(()=> {
avePopup.style.opacity = '0';
setTimeout(()=> {
avePopup.remove();
}, 200);
}, 3500);
}
}
function createTaxInfoElement(prod, index = Math.round(Math.random()* 10000)) {
console.log('Called createTaxInfo()');
let _currencySymbol = '';
if (prod.data_tax_currency && prod.data_tax_currency == 'EUR') _currencySymbol = '€';
const _taxElement = document.createElement('span');
_taxElement.setAttribute("id", `ave-taxinfo-${index}`);
_taxElement.style.cssText = 'position: relative; transform: translate(0px, -30px); width: fit-content; right: 0px;';
const _taxElement_span = document.createElement('span');
_taxElement_span.setAttribute("id", `ave-taxinfo-${index}-text`);
_taxElement_span.classList.add('ave-taxinfo-text');
const _prize = prod.data_estimated_tax_prize;
console.log('Called createTaxInfo(): We have a Taxprize of: ', _prize);
_taxElement_span.innerText = `Tax Price: ${(typeof(_prize) == 'number') ? _prize :'--.--'} ${_currencySymbol}`;
console.log('createTaxInfo(): After innerText');
_taxElement.appendChild(_taxElement_span);
console.log('createTaxInfo(): END', _taxElement);
return _taxElement;
}
function insertHtmlElementAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
async function createProductSite(siteType, productArray, cb) {
if (!productArray) return;
const _productArrayLength = productArray.length;
const _fastCount = Math.min(_productArrayLength, SETTINGS.MaxItemsPerPage);
if (SETTINGS.DebugLevel > 10) console.log(`Create Overview for ${_productArrayLength} Products`);
// Remove Pagination
const _pagination = document.querySelector('.a-pagination')
if (_pagination) _pagination.remove();
const _contentContainer = document.querySelector('.a-section.vvp-tab-content');
if(_contentContainer.querySelector('.vvp-no-offers-msg')){
_contentContainer.querySelector('.vvp-no-offers-msg').remove();
let _tileStructure = document.createElement('div');
_tileStructure.classList = 'a-section vvp-items-container';
_tileStructure.innerHTML = `
<div id="vvp-browse-nodes-container">
</div>
<div id="vvp-items-grid-container">
<p>
</p>
<div id="vvp-items-grid" class="a-section">
</div>
</div>`;
_contentContainer.appendChild(_tileStructure);
};
// Cear Left Nodes Container
const _nodesContainer = document.getElementById('vvp-browse-nodes-container');
if (_nodesContainer) _nodesContainer.innerHTML = '';
// Items Grid Container
const _tilesContainer = document.getElementById('vvp-items-grid-container');
if (!_tilesContainer) reloadPageWithSubpageTarget(siteType);
// Edit Top Line
if (_tilesContainer) {
const _topLine = _tilesContainer.getElementsByTagName('p')[0];
_topLine.innerHTML = `<p>Anzeigen von <strong>${_fastCount}</strong> von <strong>${_productArrayLength}</strong> Ergebnissen</p>`
}
const _tilesGrid = document.getElementById('vvp-items-grid');
if (!_tilesGrid) reloadPageWithSubpageTarget(siteType);
_tilesGrid.innerHTML = '';
let _index = 0;
let _returned = 0;
for (; _index < _fastCount; _index++) {
createTileFromProduct(productArray[_index], _index, (tile) => {
_tilesGrid.append(tile);
_returned++;
if (SETTINGS.DebugLevel > 10) console.log(`Created Tile (${_returned}/${_fastCount})`);
if (_returned == _fastCount) cb(true);
});
}
addLeftSideButtons(true);
}
async function createInfiniteScrollSite(siteType, cb) {
if (SETTINGS.DebugLevel > 10) console.log(`Called createInfiniteScrollSite()`);
// Remove Pagination
const _pagination = document.querySelector('.a-pagination')
if (_pagination) _pagination.remove();
const _contentContainer = document.querySelector('.a-section.vvp-tab-content');
if(_contentContainer.querySelector('.vvp-no-offers-msg')){
_contentContainer.querySelector('.vvp-no-offers-msg').remove();
let _tileStructure = document.createElement('div');
_tileStructure.classList = 'a-section vvp-items-container';
_tileStructure.innerHTML = `
<div id="vvp-browse-nodes-container">
</div>
<div id="vvp-items-grid-container">
<p>
</p>
<div id="vvp-items-grid" class="a-section">
</div>
</div>`;
_contentContainer.appendChild(_tileStructure);
};
// Cear Left Nodes Container
const _nodesContainer = document.getElementById('vvp-browse-nodes-container');
if (_nodesContainer) _nodesContainer.innerHTML = '';
// Items Grid Container
const _tilesContainer = document.getElementById('vvp-items-grid-container');
if (!_tilesContainer) reloadPageWithSubpageTarget(siteType);
// Edit Top Line
if (_tilesContainer) {
const _topLine = _tilesContainer.getElementsByTagName('p')[0];
_topLine.innerHTML = ''
}
const _tilesGrid = document.getElementById('vvp-items-grid');
if (!_tilesGrid) reloadPageWithSubpageTarget(siteType);
_tilesGrid.innerHTML = '';
addLeftSideButtons(true);
cb(_tilesGrid);
}
async function appendInfiniteScrollTiles(cb = ()=>{}){
// So lange tiles hinzufügen bis wir wieder über dem sichtbaren bereich sind
console.log('appendInfiniteScrollTiles(): ', infiniteScrollTilesBufferArray);
const _tilesContainer = document.getElementById('vvp-items-grid');
// setTimeout(async () => {
let _stopCreation = false;
let _createdCount = 0;
while (infiniteScrollTilesBufferArray.length > 0 && !_stopCreation) {
const _tile = infiniteScrollTilesBufferArray.shift();
if (SETTINGS.EnableInfiniteScrollLiveQuerry) {
_tilesContainer.appendChild(_tile);
parseTileData(_tile).then((_product) => {
if (SETTINGS.DebugLevel > 14) console.log('Come Back from parseTileData <<<<<<<<<< INFINITYSCROLL <<<<<<<<<<<<<<<<<<<<<<<', _tile, _product);
addStyleToTile(_tile, _product);
addTileEventhandlers(_tile);
});
} else {
createTileFromProduct(_tile).then((_elem) => {
_tilesContainer.appendChild(_elem);
addTileEventhandlers(_elem);
})
}
if (_createdCount++ >= 100) _stopCreation = true;
const _maxScrollHeight = Math.max(document.body.scrollHeight - window.innerHeight, document.documentElement.scrollHeight - window.innerHeight);
if (_maxScrollHeight > (window.scrollY + (window.innerHeight * 2))) _stopCreation = true;
console.log(`appendInfiniteScrollTiles(): Inside WHILE: _maxScrollHeigt: ${_maxScrollHeight} currPosition ${window.scrollY}`);
}
console.log(`appendInfiniteScrollTiles(): After WHILE: left tile to create: ${infiniteScrollTilesBufferArray.length}`);
cb(true);
// },100);
}
/**
* AVE PAGETYPE ENUM
* @readonly
* @enum {number}
*/
const PAGETYPE = {
NEW_ITEMS: 0,
FAVORITES: 1,
ALL: 2,
SEARCH_RESULT: 9,
OROGINAL_POTLUCK: 100,
ORIGINAL_LAST_CHANCE: 101,
ORIGINAL_SELLER: 102
}
function createNewSite(type, data) {
// Unhightlight nav buttons
const _btnContainer = document.getElementById('vvp-items-button-container');
const _selected = _btnContainer.getElementsByClassName('a-button-selected');
for (let i = 0; i < _selected.length; i++) {
const _btn = _selected[i];
_btn.classList.remove("a-button-selected");
_btn.classList.add("a-button-normal");
_btn.removeAttribute('aria-checked');
}
switch(type) {
case PAGETYPE.NEW_ITEMS:{
currentMainPage = PAGETYPE.NEW_ITEMS;
database.getNewEntries().then((_prodArr) => {
createProductSite(type, _prodArr, () => {
initTileEventHandlers();
const _btn = document.getElementById('ave-btn-list-new');
_btn.classList.add('a-button-selected');
_btn.setAttribute('aria-checked', true);
});
})
break;
}
case PAGETYPE.FAVORITES:{
currentMainPage = PAGETYPE.FAVORITES;
database.getFavEntries().then((_prodArr) => {
createProductSite(type, _prodArr, () => {
initTileEventHandlers();
const _btn = document.getElementById('ave-btn-favorites');
_btn.classList.add('a-button-selected');
_btn.setAttribute('aria-checked', true);
});
})
break;
}
case PAGETYPE.ALL:{
currentMainPage = PAGETYPE.ALL;
createInfiniteScrollSite(currentMainPage,(tilesContainer) => {
const _baseUrl = (/(http[s]{0,1}\:\/\/[w]{0,3}.amazon.[a-z]{1,}.{0,1}[a-z]{0,}\/vine\/vine-items)/.exec(window.location.href))[1];
const _preloadPages = ['potluck', 'last_chance', 'encore']
infiniteScrollLastPreloadedPage = 1;
infiniteScrollMaxPreloadPage = 100;
infiniteScrollTilesBufferArray = [];
if (SETTINGS.EnableInfiniteScrollLiveQuerry) {
getTilesFromURL(`${_baseUrl}?queue=${_preloadPages[0]}`, (tiles1) =>{
infiniteScrollTilesBufferArray = infiniteScrollTilesBufferArray.concat(tiles1);
appendInfiniteScrollTiles();
getTilesFromURL(`${_baseUrl}?queue=${_preloadPages[1]}`, (tiles2) =>{
infiniteScrollTilesBufferArray = infiniteScrollTilesBufferArray.concat(tiles2);
appendInfiniteScrollTiles();
getTilesFromURL(`${_baseUrl}?queue=${_preloadPages[2]}`, (tiles3) =>{
infiniteScrollTilesBufferArray = infiniteScrollTilesBufferArray.concat(tiles3);
appendInfiniteScrollTiles();
setTimeout(()=> {
handleInfiniteScroll(); // Just to trigger first preloads
}, 500);
})
})
})
} else {
database.getAll().then((prodArr) => {
infiniteScrollTilesBufferArray = prodArr;
appendInfiniteScrollTiles();
});
}
});
break;
}
case PAGETYPE.SEARCH_RESULT:{
currentMainPage = PAGETYPE.SEARCH_RESULT;
createProductSite(type, data, () => {
initTileEventHandlers();
});
break;
}
}
}
let lastGetTilesFromURLQuerry = 0;
function getTilesFromURL(url, cb = (tilesArray) => {}) {
if (lastGetTilesFromURLQuerry + SETTINGS.PageLoadMinDelay > Date.now()) {
const _delay = Math.max(1, lastGetTilesFromURLQuerry + SETTINGS.PageLoadMinDelay - Date.now());
console.warn(`getTilesFromURL() DELAYED for ${_delay}ms`)
setTimeout(() => {getTilesFromURL(url, cb)}, _delay);
return;
}
GM.xmlHttpRequest({