-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathShow_metacritic_ratings.user.js
More file actions
3438 lines (3173 loc) · 129 KB
/
Copy pathShow_metacritic_ratings.user.js
File metadata and controls
3438 lines (3173 loc) · 129 KB
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 Show Metacritic.com ratings
// @description Show metacritic metascore and user ratings on: Bandcamp, Apple Itunes (Music), Amazon (Music,Movies,TV Shows), IMDb (Movies), Google Play (Music, Movies), Steam, Gamespot (PS4, XONE, PC), Rotten Tomatoes, Serienjunkies, BoxOfficeMojo, allmovie.com, fandango.com, Wikipedia (en), themoviedb.org, letterboxd, TVmaze, TVGuide, followshows.com, TheTVDB.com, ConsequenceOfSound, Pitchfork, Last.fm, TVnfo, rateyourmusic.com, GOG, Epic Games Store, save.tv
// @namespace cuzi
// @icon https://www.metacritic.com/a/img/favicon.svg
// @supportURL https://github.com/cvzi/Metacritic-userscript/issues
// @contributionURL https://buymeacoff.ee/cuzi
// @contributionURL https://ko-fi.com/cuzicvzi
// @grant unsafeWindow
// @grant GM.xmlHttpRequest
// @grant GM.setValue
// @grant GM.getValue
// @grant GM.registerMenuCommand
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js
// @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt
// @antifeature tracking When a metacritic rating is displayed, we may store the url of the current website and the metacritic url in our database. Log files are temporarily retained by our database hoster Cloudflare Workers® and contain your IP address and browser configuration.
// @version 112
// @connect metacritic.com
// @connect backend.metacritic.com
// @connect met.acritic.workers.dev
// @connect imdb.com
// @match https://*.bandcamp.com/*
// @match https://play.google.com/store/music/album/*
// @match https://play.google.com/store/movies/details/*
// @match https://music.amazon.com/*
// @match https://www.amazon.ca/*
// @match https://www.amazon.co.jp/*
// @match https://www.amazon.co.uk/*
// @match https://smile.amazon.co.uk/*
// @match https://www.amazon.com.au/*
// @match https://www.amazon.com.mx/*
// @match https://www.amazon.com/*
// @match https://smile.amazon.com/*
// @match https://www.amazon.de/*
// @match https://smile.amazon.de/*
// @match https://www.amazon.es/*
// @match https://www.amazon.fr/*
// @match https://www.amazon.in/*
// @match https://www.amazon.it/*
// @match https://www.imdb.com/title/*
// @match https://store.steampowered.com/app/*
// @match https://www.gamespot.com/*
// @match https://www.serienjunkies.de/*
// @match https://www.rottentomatoes.com/m/*
// @match https://rottentomatoes.com/m/*
// @match https://www.rottentomatoes.com/tv/*
// @match https://rottentomatoes.com/tv/*
// @match https://www.rottentomatoes.com/tv/*
// @match https://rottentomatoes.com/tv/*
// @match https://www.boxofficemojo.com/movies/*
// @match https://www.boxofficemojo.com/release/*
// @match https://www.allmovie.com/movie/*
// @match https://en.wikipedia.org/*
// @match https://www.fandango.com/*
// @match https://www.themoviedb.org/movie/*
// @match https://www.themoviedb.org/tv/*
// @match https://letterboxd.com/film/*
// @match https://www.tvmaze.com/shows/*
// @match https://www.tvguide.com/tvshows/*
// @match https://followshows.com/show/*
// @match https://thetvdb.com/series/*
// @match https://thetvdb.com/movies/*
// @match https://consequenceofsound.net/*
// @match https://consequence.net/*
// @match https://pitchfork.com/*
// @match https://www.last.fm/*
// @match https://tvnfo.com/tv/*
// @match https://rateyourmusic.com/release/album/*
// @match https://open.spotify.com/*
// @match https://play.spotify.com/album/*
// @match https://www.nme.com/reviews/*
// @match https://www.albumoftheyear.org/album/*
// @match https://itunes.apple.com/*
// @match https://music.apple.com/*
// @match https://epguides.com/*
// @match https://www.epguides.com/*
// @match https://www.netflix.com/*
// @match https://www.cc.com/*
// @match https://www.amc.com/*
// @match https://www.amcplus.com/*
// @match https://rlsbb.ru/*/
// @match https://newalbumreleases.net/*
// @match https://www.sho.com/*
// @match https://www.epicgames.com/store/*
// @match https://store.epicgames.com/*
// @match https://www.gog.com/*
// @match https://www.allmusic.com/album/*
// @match https://www.steamgifts.com/giveaway/*
// @match https://psa.wf/*
// @match https://www.save.tv/*
// @match https://www.wikiwand.com/*
// @match https://trakt.tv/*
// @match http://localhost:7878/*
// ==/UserScript==
/* globals alert, confirm, GM, DOMParser, $, Image, unsafeWindow, parent, Blob, failedImages */
/* jshint asi: true, esversion: 8 */
const scriptName = 'Show Metacritic.com ratings'
const baseURL = 'https://www.metacritic.com/'
const baseURLmusic = 'https://www.metacritic.com/music/'
const baseURLmovie = 'https://www.metacritic.com/movie/'
const baseURLpcgame = 'https://www.metacritic.com/game/'
const baseURLps4 = 'https://www.metacritic.com/game/'
const baseURLxone = 'https://www.metacritic.com/game/'
const baseURLtv = 'https://www.metacritic.com/tv/'
// const baseURLsearch = 'https://backend.metacritic.com/finder/metacritic/search/{query}/web?apiKey={apiKey}&componentName=search-tabs&componentDisplayName=Search+Page+Tab+Filters&componentType=FilterConfig&mcoTypeId={type}&offset=0&limit=30'
const baseURLsearch = 'https://backend.metacritic.com/finder/metacritic/search/{query}/web?componentName=search-tabs&componentDisplayName=Search+Page+Tab+Filters&componentType=FilterConfig&mcoTypeId={type}&offset=0&limit=30'
const baseURLdatabase = 'https://met.acritic.workers.dev/r.php'
const baseURLwhitelist = 'https://met.acritic.workers.dev/whitelist.php'
const baseURLblacklist = 'https://met.acritic.workers.dev/blacklist.php'
const TEMPORARY_BLACKLIST_TIMEOUT = 5 * 60
const windowPositions = [
{
bottom: 0,
left: 0
},
{
bottom: 0,
right: 0
},
{
top: 0,
right: 0
},
{
top: 0,
left: 0
}
]
// Detect dark theme of darkreader.org extension
const darkTheme = 'darkreaderScheme' in document.documentElement.dataset && document.documentElement.dataset.darkreaderScheme
let myDOMParser = null
function domParser () {
if (myDOMParser === null) {
myDOMParser = new DOMParser()
}
return myDOMParser
}
async function versionUpdate () {
const version = parseInt(await GM.getValue('version', 0))
if (version <= 105) {
// Reset database
await GM.setValue('map', '{}')
await GM.setValue('black', '[]')
await GM.setValue('hovercache', '{}')
await GM.setValue('requestcache', '{}')
await GM.setValue('temporaryblack', '{}')
await GM.setValue('searchcache', false) // Unused
await GM.setValue('autosearchcache', false) // Unused
}
if (version < 106) {
await GM.setValue('version', 106)
}
}
const BOX_CSS_DARK_THEME = `
#mcdiv123 {
position: fixed;
background-color: #262626;
border: 2px solid #313131;
color: white;
}
#mcisearchquery {
background: #262626;
color: white;
}
#mcisearchbutton {
background: rgb(56, 56, 56);
color: white;
border: 2px solid white;
}
#mcdiv123 .grespinner {
border-left: 6px solid rgba(0,174,239,.15);
border-right: 6px solid rgba(0,174,239,.15);
border-bottom: 6px solid rgba(0,174,239,.15);
border-top: 6px solid rgba(0,174,239,.8);
}
#mcdiv123searchresults .result {
border-top-color: #525252;
}
#mcdiv123searchresults .result .mcdiv123_score_badge {
color: white;
}
#mcdiv123searchresults .result .mcdiv_release_date {
color: silver
}
.mcdiv123_image_placeholder {
background: rgb(64, 64, 64);
}
#mcdiv123searchresults .result a {
color: #09f;
}
#mcdiv123searchresults .mcdiv_desc {
scrollbar-color: #003c09 #00ce7a;
}
#mcdiv123searchresults .mcdiv_desc::-webkit-scrollbar-thumb {
background-color: #003c09;
}
`
const BOX_CSS = `
#mcdiv123 {
position: fixed;
background-color: #fff;
border: 2px solid #bbb;
border-radius: 6px;
box-shadow: 0 0 3px 3px rgba(100, 100, 100, 0.2);
color: #000;
min-width: 150;
max-height: 80%;
max-width: 640;
overflow: auto;
padding: 3px;
z-index: 2147483601;
}
#mcisearchquery {
background: white;
color: black;
width: 450px;
display: inline;
}
#mcisearchbutton {
background: silver;
color: black;
border: 2px solid black;
padding: 3px;
display: inline;
margin: 0px 5px;
cursor: pointer;
}
/* http://www.designcouch.com/home/why/2013/05/23/dead-simple-pure-css-loading-spinner/ */
#mcdiv123 .grespinner {
display: inline-block;
height: 20px;
width: 20px;
margin: 0 auto;
position: relative;
animation: rotation .6s infinite linear;
border-left: 6px solid rgba(0,174,239,.15);
border-right: 6px solid rgba(0,174,239,.15);
border-bottom: 6px solid rgba(0,174,239,.15);
border-top: 6px solid rgba(0,174,239,.8);
border-radius: 100%
}
@keyframes rotation {
from {
transform: rotate(0)
}
to {
transform: rotate(359deg)
}
}
#mcdiv123searchresults {
font-size: 12px;
max-width: 95%
}
.mcdiv123_correct_entry {
cursor: pointer;
color: green;
font-size: 25px;
margin-top: 10px;
}
.mcdiv123_correct_entry:hover {
color: #41fd41;
}
.mcdiv123_incorrect {
cursor: pointer;
float: right;
color: crimson;
font-size: 11px;
}
.mcdiv123_incorrect {
cursor: pointer;
float: right;
color: crimson;
font-size: 15px;
margin-right: 10px;
}
.mcdiv123_incorrect:hover {
cursor: pointer;
float: right;
color: crimson;
font-size: 15px;
margin-right: 10px;
border:2px solid white;
}
.mcdiv123_incorrect:hover {
border-color: crimson;
}
#mcdiv123searchresults .result {
font: 12px arial,helvetica,serif;
border-top-width: 1px;
border-top-color: #ccc;
border-top-style: solid;
padding: 5px
}
.mcdiv123_cover {
max-width: 200px;
max-height: 140px;
}
#mcdiv123searchresults .result .mcdiv123_score_badge {
display: inline-block;
margin: 3px;
font-weight: 600;
border-radius: 6px;
color: black;
padding: 5px;
}
#mcdiv123searchresults .result .floatleft {
float: left;
}
#mcdiv123searchresults .result .clearleft {
clear: left;
}
#mcdiv123searchresults .result .resultcontent {
max-width: 360px;
margin-left: 10px;
}
#mcdiv123searchresults .result .mcdiv_release_date {
color: silver
}
.mcdiv123_image_placeholder {
width: 82px;
height: 82px;
background: rgb(64, 64, 64);
border-radius: 8px;
}
#mcdiv123searchresults .result a {
color: #09f;
font-weight: 700;
text-decoration: none
}
#mcdiv123searchresults .mcdiv_desc {
max-height:120px;
overflow-y: auto;
scrollbar-color: #d9d9d9 #eee;
scrollbar-width: thin;
}
@media (prefers-color-scheme: dark) {
${BOX_CSS_DARK_THEME}
}
${
darkTheme ? BOX_CSS_DARK_THEME : ''
}
`
async function acceptGDPR (showDialog) {
if (showDialog === true) {
await GM.setValue('gdpr', null)
return acceptGDPR()
}
return new Promise(function (resolve) {
GM.getValue('gdpr', null).then(function (value) {
if (value === true) {
return resolve(true)
}
if (value === false) {
return resolve(false)
}
const html = '<h1>Privacy Policy for "Show Metacritic.com ratings"</h1><h2>General Data Protection Regulation (GDPR)</h2><p>We are a Data Controller of your information.</p> <p>"Show Metacritic.com ratings" legal basis for collecting and using the personal information described in this Privacy Policy depends on the Personal Information we collect and the specific context in which we collect the information:</p><ul> <li>"Show Metacritic.com ratings" needs to perform a contract with you</li> <li>You have given "Show Metacritic.com ratings" permission to do so</li> <li>Processing your personal information is in "Show Metacritic.com ratings" legitimate interests</li> <li>"Show Metacritic.com ratings" needs to comply with the law</li></ul> <p>"Show Metacritic.com ratings" will retain your personal information only for as long as is necessary for the purposes set out in this Privacy Policy. We will retain and use your information to the extent necessary to comply with our legal obligations, resolve disputes, and enforce our policies.</p> <p>If you are a resident of the European Economic Area (EEA), you have certain data protection rights. If you wish to be informed what Personal Information we hold about you and if you want it to be removed from our systems, please contact us. Our Privacy Policy was generated with the help of <a href="https://www.gdprprivacypolicy.net/">GDPR Privacy Policy Generator</a> and the <a href="https://www.app-privacy-policy.com">App Privacy Policy Generator</a>.</p><p>In certain circumstances, you have the following data protection rights:</p><ul> <li>The right to access, update or to delete the information we have on you.</li> <li>The right of rectification.</li> <li>The right to object.</li> <li>The right of restriction.</li> <li>The right to data portability</li> <li>The right to withdraw consent</li></ul><h2>Log Files</h2><p>"Show Metacritic.com ratings" follows a standard procedure of using log files. These files log visitors when they visit websites. All hosting companies do this and a part of hosting services\' analytics. The information collected by log files include internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date and time stamp, referring/exit pages, and possibly the number of clicks. These are not linked to any information that is personally identifiable. The purpose of the information is for analyzing trends, administering the site, tracking users\' movement on the website, and gathering demographic information.</p><h2>Privacy Policies</h2><P>You may consult this list to find the Privacy Policy for each of the advertising partners of "Show Metacritic.com ratings".</p><p>Third-party ad servers or ad networks uses technologies like cookies, JavaScript, or Web Beacons that are used in their respective advertisements and links that appear on "Show Metacritic.com ratings", which are sent directly to users\' browser. They automatically receive your IP address when this occurs. These technologies are used to measure the effectiveness of their advertising campaigns and/or to personalize the advertising content that you see on websites that you visit.</p><p>Note that "Show Metacritic.com ratings" has no access to or control over these cookies that are used by third-party advertisers.</p><h2>Third Party Privacy Policies</h2><p>"Show Metacritic.com ratings"\'s Privacy Policy does not apply to other advertisers or websites. Thus, we are advising you to consult the respective Privacy Policies of these third-party ad servers for more detailed information. It may include their practices and instructions about how to opt-out of certain options.List of these Privacy Policies and their links: <ul> <li>Cloudflare Workers®: <a href="https://www.cloudflare.com/privacypolicy/">https://www.cloudflare.com/privacypolicy/</a></li> <li>www.metacritic.com: <a href="https://privacy.cbs/">https://privacy.cbs/</a></li></ul></p><p>You can choose to disable cookies through your individual browser options.</p><h2>Children\'s Information</h2><p>Another part of our priority is adding protection for children while using the internet. We encourage parents and guardians to observe, participate in, and/or monitor and guide their online activity.</p><p>"Show Metacritic.com ratings" does not knowingly collect any Personal Identifiable Information from children under the age of 13. If you think that your child provided this kind of information on our website, we strongly encourage you to contact us immediately and we will do our best efforts to promptly remove such information from our records.</p><h2>Online Privacy Policy Only</h2><p>Our Privacy Policy created at GDPRPrivacyPolicy.net) applies only to our online activities and is valid for users of our program with regards to the information that they shared and/or collect in "Show Metacritic.com ratings". This policy is not applicable to any information collected offline or via channels other than this program. <a href="https://gdprprivacypolicy.net">Our GDPR Privacy Policy</a> was generated from the GDPR Privacy Policy Generator.</p><h2>Contact</h2><p>Contact us via github <a href="https://github.com/cvzi/Metacritic-userscript">https://github.com/cvzi/Metacritic-userscript</a> or email cuzi@openmail.cc</p><h2>Consent</h2><p>By using our program ("userscript"), you hereby consent to our Privacy Policy and agree to its terms.</p>'
const div = document.body.appendChild(document.createElement('div'))
div.innerHTML = html
div.style = 'z-index:9999;position:absolute;min-height:100%;top:0px; left:0px; right:0px; padding:10px; background:white; color:black; font-family:serif; font-size:16px'
div.appendChild(document.createElement('br'))
const acceptButton = div.appendChild(document.createElement('button'))
acceptButton.setAttribute('style', 'color:black;background:#e5e4e4;border:2px #bbb outset;margin:5px;padding:2px 10px;font-size:16px;font-family:sans-serif;cursor:pointer')
acceptButton.appendChild(document.createTextNode('Accept'))
acceptButton.addEventListener('click', function () {
div.remove()
resolve(true)
GM.setValue('gdpr', true)
})
const declineButton = div.appendChild(document.createElement('button'))
declineButton.setAttribute('style', 'color:black;background:#e5e4e4;border:2px #bbb outset;margin:5px;padding:2px 10px;font-size:16px;font-family:sans-serif;cursor:pointer')
declineButton.appendChild(document.createTextNode('Decline'))
declineButton.addEventListener('click', function () {
alert('You may uninstall the userscript now.')
div.remove()
resolve(false)
GM.setValue('gdpr', false)
})
const space = div.appendChild(document.createElement('div'))
space.style = 'height:2000px;'
div.scrollIntoView()
window.setTimeout(function () {
alert('ShowMetacriticRatings:\n\nWhen you use this script, data will be sent to our database and to metacritic.com. This data includes the url of the website that you are browsing, the metacritic page url, your IP adress, browser configuration and language preferences. We only store the url of the website and the metacritic url and no personal information. Log files are temporarily retained and contain your IP address. We have no control over which data is stored by metacritic.com and our hoster heroku.com, see their respective privacy policies for more information (see "Third Party Privacy Policies").\n\nPlease read and accept our privacy policy now or uninstall this userscript.')
}, 20)
})
})
}
function delay (ms) {
return new Promise(function (resolve) {
window.setTimeout(() => resolve(), ms)
})
}
function absoluteMetaURL (url) {
if (url.startsWith('https://')) {
return url
}
if (url.startsWith('http://')) {
return 'https' + url.substr(4)
}
if (url.startsWith('//')) {
return baseURL + url.substr(2)
}
if (url.startsWith('/')) {
return baseURL + url.substr(1)
}
url = url.replace('/game/pc/', '/game/').replace(/\/game\/playstation-\d\//, '/game/').replace('/game/xbox-one/', '/game/')
return baseURL + url
}
const parseLDJSONCache = {}
function parseLDJSON (keys, condition) {
if (document.querySelector('script[type="application/ld+json"]')) {
const xmlEntitiesElement = document.createElement('div')
const xmlEntitiesPattern = /&(?:#x[a-f0-9]+|#[0-9]+|[a-z0-9]+);?/ig
const xmlEntities = function (s) {
s = s.replace(xmlEntitiesPattern, (m) => {
xmlEntitiesElement.innerHTML = m
return xmlEntitiesElement.textContent
})
return s
}
const decodeXmlEntities = function (jsonObj) {
// Traverse through object, decoding all strings
if (jsonObj !== null && typeof jsonObj === 'object') {
Object.entries(jsonObj).forEach(([key, value]) => {
// key is either an array index or object key
jsonObj[key] = decodeXmlEntities(value)
})
} else if (typeof jsonObj === 'string') {
return xmlEntities(jsonObj)
}
return jsonObj
}
const data = []
const scripts = document.querySelectorAll('script[type="application/ld+json"]')
for (let i = 0; i < scripts.length; i++) {
let jsonld
if (scripts[i].innerText in parseLDJSONCache) {
jsonld = parseLDJSONCache[scripts[i].innerText]
} else {
let text
try {
text = scripts[i].innerText
text = text.replace(/^\/\*.*\*\//gm, '') // Replace comment lines
jsonld = JSON.parse(text)
parseLDJSONCache[scripts[i].innerText] = jsonld
} catch (e) {
parseLDJSONCache[scripts[i].innerText] = null
console.warn(e, text)
continue
}
}
if (jsonld) {
if (Array.isArray(jsonld)) {
data.push(...jsonld)
} else {
data.push(jsonld)
}
}
}
for (let i = 0; i < data.length; i++) {
try {
if (data[i] && data[i] && (typeof condition !== 'function' || condition(data[i]))) {
if (Array.isArray(keys)) {
const r = []
for (let j = 0; j < keys.length; j++) {
r.push(data[i][keys[j]])
}
return decodeXmlEntities(r)
} else if (keys) {
return decodeXmlEntities(data[i][keys])
} else if (typeof condition === 'function') {
return decodeXmlEntities(data[i]) // Return whole object
}
}
} catch (e) {
continue
}
}
return decodeXmlEntities(data)
}
return null
}
function name2metacritic (s) {
const mc = s.normalize('NFKD').replace(/\//g, '').replace(/[\u0300-\u036F]/g, '').replace(/&/g, 'and').replace(/\W+/g, ' ').toLowerCase().trim().replace(/\W+/g, '-')
if (!mc) {
throw new Error("name2metacritic converted '" + s + "' to empty string")
}
return mc
}
function minutesSince (time) {
const seconds = ((new Date()).getTime() - time.getTime()) / 1000
return seconds > 60 ? parseInt(seconds / 60) + ' min ago' : 'now'
}
function randomStringId () {
const id10 = () => Math.floor((1 + Math.random()) * 0x10000000000).toString(16).substring(1)
return id10() + id10() + id10() + id10() + id10() + id10()
}
function fixMetacriticURLs (html) {
return html.replace(/<a /g, '<a target="_blank" ').replace(/href="\//g, 'href="' + baseURL).replace(/src="\//g, 'src="' + baseURL)
}
function searchType2fandomProdApigee (type) {
return ({
tv: '1',
movie: '2',
pcgame: '13',
xonegame: '13',
ps4game: '13',
music: '4' // TODO this is probably wrong, music seems to be unsupported at the moment
})[type]
}
function fandomProdApigee2metacriticUrl (type) {
return ({
1: 'tv',
2: 'movie',
13: 'game',
4: 'music' // TODO this is probably wrong, music seems to be unsupported at the moment
})[type]
}
function badgeColor (score, type = '') {
const colors = {
universalAcclaim: '#6c3',
generallyFavorable: '#00ce7a',
mixedOrAverage: '#ffbd3f',
generallyUnfavorable: '#ff6874',
overwhelmingDislike: '#f00',
tbd: '#fff'
}
if (type.indexOf('game') !== -1) {
if (score > 89) {
return colors.universalAcclaim
}
if (score > 74) {
return colors.generallyFavorable
}
if (score > 49) {
return colors.mixedOrAverage
}
if (score > 19) {
return colors.generallyUnfavorable
}
if (score > 0) {
return colors.overwhelmingDislike
}
return colors.tbd
} else {
if (score > 80) {
return colors.universalAcclaim
}
if (score > 60) {
return colors.generallyFavorable
}
if (score > 39) {
return colors.mixedOrAverage
}
if (score > 19) {
return colors.generallyUnfavorable
}
if (score > 0) {
return colors.overwhelmingDislike
}
return colors.tbd
}
}
function replaceBrackets (str) {
str = str.replace(/\([^(]*\)/g, '')
str = str.replace(/\[[^\]]*\]/g, '')
return str.trim()
}
function removeSymbols (str) {
str = str.replace(/[^\s0-9A-Za-zÀ-ÖØ-öø-ÿ]*/gi, '').trim()
return str.trim()
}
const dashRegExp = /[-\u2010\u2011\u2012\u2013\u2014\u2015\uFE58\uFE63\uFF0D]/
function removeAnythingAfterDash (str) {
str = str.split(dashRegExp)[0]
return str.trim()
}
function broadenSearch (data, step, type) {
if (type === 'pcgame') {
if (step > 0) {
data[0] = replaceBrackets(data[0])
} else if (step > 1) {
data[0] = removeSymbols(data[0])
} else if (step > 2) {
data[0] = removeAnythingAfterDash(data[0])
}
} else {
data = data.map(removeSymbols)
}
return data
}
function balloonAlert (message, timeout, title, css, click) {
let header
if (title) {
header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">' + title + '</div>'
} else if (title === false) {
header = ''
} else {
header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">Userscript alert</div>'
}
const div = $('<div>' + header + '<div style="padding:5px">' + message.split('\n').join('<br>') + '</div></div>')
div.css({
position: 'fixed',
top: 10,
left: 10,
maxWidth: 200,
zIndex: '2147483601',
background: 'rgb(240,240,240)',
border: '2px solid yellow',
borderRadius: '6px',
boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
fontFamily: 'sans-serif',
color: 'black'
})
if (css) {
div.css(css)
}
div.appendTo(document.body)
if (click) {
div.click(function (ev) {
$(this).hide(500)
click.call(this, ev)
})
}
if (!click) {
const close = $('<div title="Close" style="cursor:pointer; position:absolute; top:0px; right:3px;">❎</div>').appendTo(div)
close.click(function () {
$(this.parentNode).hide(1000)
})
}
if (timeout && timeout > 0) {
window.setTimeout(function () {
div.hide(3000)
}, timeout)
}
return div
}
function filterUniversalUrl (url) {
try {
url = url.match(/http.+/)[0]
} catch (e) { }
try {
url = url.replace(/https?:\/\/(www.)?/, '')
} catch (e) { }
if (url.indexOf('#') !== -1) {
url = url.split('#')[0]
}
if (url.startsWith('imdb.com/') && url.match(/(imdb\.com\/\w+\/\w+\/)/)) {
// Remove movie subpage from imdb url
return url.match(/(imdb\.com\/\w+\/\w+\/)/)[1]
} else if (url.startsWith('boxofficemojo.com/') && url.indexOf('id=') !== -1) {
// Keep the important id= on
try {
const parts = url.split('?')
const page = parts[0] + '?'
const idparam = parts[1].match(/(id=.+?)(\.|&)/)[1]
return page + idparam
} catch (e) {
return url
}
} else {
// Default: Remove parameters
return url.split('?')[0].split('&')[0]
}
}
async function addToMap (url, metaurl) {
const data = JSON.parse(await GM.getValue('map', '{}'))
url = filterUniversalUrl(url)
metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
data[url] = metaurl
await GM.setValue('map', JSON.stringify(data));
(new Image()).src = baseURLwhitelist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId())
return [url, metaurl]
}
async function addToTemporaryBlacklist (metaurl) {
const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
metaurl = metaurl.replace(/^\/+/, '')
data[metaurl] = (new Date()).toJSON()
// Remove old entries
const now = (new Date()).getTime()
const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000
for (const prop in data) {
if (now - (new Date(data[prop].time)).getTime() > timeout) {
delete data[prop]
}
}
await GM.setValue('temporaryblack', JSON.stringify(data))
return true
}
async function removeFromTemporaryBlacklist (metaurl) {
const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
metaurl = metaurl.replace(/^\/+/, '')
if (metaurl in data) {
delete data[metaurl]
await GM.setValue('temporaryblack', JSON.stringify(data))
}
}
async function isTemporaryBlacklisted (metaurl) {
const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
metaurl = metaurl.replace(/^\/+/, '')
if (metaurl in data) {
const now = (new Date()).getTime()
const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000
if (now - (new Date(data[metaurl])).getTime() < timeout) {
return true
}
}
return false
}
async function addToBlacklist (url, metaurl) {
const data = JSON.parse(await GM.getValue('black', '[]'))
url = filterUniversalUrl(url)
metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
data.push([url, metaurl])
await GM.setValue('black', JSON.stringify(data));
(new Image()).src = baseURLblacklist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId())
return [url, metaurl]
}
async function removeFromBlacklist (docurl, metaurl) {
docurl = filterUniversalUrl(docurl)
docurl = docurl.replace(/https?:\/\/(www.)?/, '')
metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash
metaurl = metaurl.replace(/^\/+/, '') // remove starting slash
const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
const found = []
for (let i = 0; i < data.length; i++) {
if (data[i][0] === docurl && data[i][1] === metaurl) {
found.push(i)
}
}
for (let i = found.length - 1; i >= 0; i--) {
data.pop(i)
}
await GM.setValue('black', JSON.stringify(data))
}
async function isBlacklistedUrl (docurl, metaurl) {
docurl = filterUniversalUrl(docurl)
docurl = docurl.replace(/https?:\/\/(www.)?/, '')
metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash
metaurl = metaurl.replace(/^\/+/, '') // remove starting slash
const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
for (let i = 0; i < data.length; i++) {
if (data[i][0] === docurl && data[i][1] === metaurl) {
return true
}
}
return false
}
let listenForHotkeysActive = false
function listenForHotkeys (code, cb) {
// Call cb() as soon as the code sequence was typed
if (listenForHotkeysActive) {
return
}
listenForHotkeysActive = true
let i = 0
$(document).bind('keydown.listenForHotkeys', function (ev) {
if (document.activeElement === document.body) {
if (ev.key !== code[i]) {
i = 0
} else {
i++
if (i === code.length) {
ev.preventDefault()
$(document).unbind('keydown.listenForHotkeys')
cb()
}
}
}
})
}
function waitForHotkeysMETA () {
listenForHotkeys('meta', (ev) => openSearchBox())
}
async function handleJSONredirect (response) {
let blacklistedredirect = false
const j = JSON.parse(response.responseText)
// Blacklist items from database received?
if ('blacklist' in j && j.blacklist && j.blacklist.length) {
// Save new blacklist items
const data = JSON.parse(await GM.getValue('black', '[]'))
for (let i = 0; i < j.blacklist.length; i++) {
const saveDocurl = j.blacklist[i].docurl
const saveMetaurl = j.blacklist[i].metaurl
data.push([saveDocurl, saveMetaurl])
if (j.jsonRedirect === '/' + saveMetaurl) {
// Redirect is blacklisted!
blacklistedredirect = true
}
}
await GM.setValue('black', JSON.stringify(data))
}
if (blacklistedredirect) {
// Redirect was blacklisted, show nothing
console.debug('ShowMetacriticRatings: Redirect was blacklisted -> show nothing')
return null
} else {
// Load redirect
current.metaurl = absoluteMetaURL(j.jsonRedirect)
response = await asyncRequest({
url: current.metaurl
}).catch(function (response) {
console.error('ShowMetacriticRatings: Error 01')
})
return response
}
}
function extractHoverFromFullPage (response) {
let html = 'ShowMetacriticRatings:<br>Error occured in extractHoverFromFullPage()'
const styleSheetUrls = []
try {
// Try parsing HTML
const doc = domParser().parseFromString(response.responseText, 'text/html')
const base = doc.createElement('base')
base.href = baseURL
doc.head.appendChild(base)
doc.head.querySelectorAll('link[rel="stylesheet"][href]').forEach(l => {
styleSheetUrls.push(l.href)
})
// Remove user rating slider
doc.querySelector('.user-score').remove()
let content = null
// Try to get the review containers from the bottom of the page below the actors
const carouselItems = doc.querySelectorAll('.carouselContainer .reviews-overview__details,.top-user-reviews-section .reviews-overview__details')
if (carouselItems.length > 0) {
content = Array.from(carouselItems).map(e => e.outerHTML).join('\n\n')
} else {
// Fallback: Try to get the review containers from the right side of the page next to the poster/screenshot
content = doc.querySelector('.product-hero__scores').innerHTML
}
// Get the current platform title:
if (doc.querySelector('.c-hero-platform-selector__label title')) {
content = `<div class="mci_current_platform_title">Platform: ${doc.querySelector('.c-hero-platform-selector__label title').textContent}</div>\n\n${content}`
}
// Get the game row with the other platform scores
const gameRow = doc.querySelector('.game-platforms__list')
if (gameRow) {
// Get the currently selected platform from the "Critic Reviews View All" link
const latestCriticReviewsLink = doc.querySelector('a.global-section-header__view-all[href*="platform="]')
let platform = null
if (latestCriticReviewsLink) {
platform = latestCriticReviewsLink.href.match(/platform=([^&]+)/)[1]
content += `\n\n<input type="hidden" id="mci_current_platform" value="${platform}"/>`
}
// Remove platforms that don't have a score
gameRow.querySelectorAll('.product-score-card[to]').forEach(e => e.remove())
// Remove the currently selected platform
if (platform) {
gameRow.querySelectorAll(`a.product-score-card[href*="platform=${platform}"]`).forEach(e => e.remove())
}
// Replace the platform icon with the platform name
gameRow.querySelectorAll('.game-platform-logo').forEach(e => {
if (e.querySelector('svg title')) {
e.textContent = e.querySelector('svg title').textContent
}
})
content += `\n\n<div class="game_row_5456d45" style="display:none">${gameRow.innerHTML}</div>`
}
if (!content) {
throw new Error('No content found')
}
html = `
<div id="hover_div_a20230915">
${content}
</div>
`
} catch (e) {
console.warn('ShowMetacriticRatings: Error parsing HTML: ' + e)
// fallback to cutting out the relevant parts
try {
console.debug('ShowMetacriticRatings: Trying to cut relevant content out of full page')
const part = response.responseText.split('class="product-hero--right-group"')[1].split('class="user-score"')[0]
html = '<div ' + part + '</div></div>'
if (html.length > 5000) {
// Probably something went wrong, let's cut the response to prevent too long content
console.warn('ShowMetacriticRatings: Cutting response to 5000 chars')
html = html.substring(0, 5000)
}
} catch (e) {
console.warn('ShowMetacriticRatings: Cutting failed')
}
}
if (styleSheetUrls) {
styleSheetUrls.forEach(url => {
console.debug('ShowMetacriticRatings: Adding stylesheet', url)