-
Notifications
You must be signed in to change notification settings - Fork 11
/
imdb-tomatoes.user.js
1829 lines (1533 loc) · 53 KB
/
imdb-tomatoes.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 IMDb Tomatoes
// @description Add Rotten Tomatoes ratings to IMDb movie and TV show pages
// @author chocolateboy
// @copyright chocolateboy
// @version 7.1.1
// @namespace https://github.com/chocolateboy/userscripts
// @license GPL
// @include /^https://www\.imdb\.com/title/tt[0-9]+/([#?].*)?$/
// @require https://code.jquery.com/jquery-3.7.1.min.js
// @require https://cdn.jsdelivr.net/gh/urin/jquery.balloon.js@8b79aab63b9ae34770bfa81c9bfe30019d9a13b0/jquery.balloon.js
// @require https://unpkg.com/dayjs@1.11.13/dayjs.min.js
// @require https://unpkg.com/dayjs@1.11.13/plugin/relativeTime.js
// @require https://unpkg.com/@chocolateboy/uncommonjs@3.2.1/dist/polyfill.iife.min.js
// @require https://unpkg.com/@chocolatey/enumerator@1.1.1/dist/index.umd.min.js
// @require https://unpkg.com/@chocolatey/when@1.2.0/dist/index.umd.min.js
// @require https://unpkg.com/dset@3.1.4/dist/index.min.js
// @require https://unpkg.com/fast-dice-coefficient@1.0.3/dice.js
// @require https://unpkg.com/get-wild@3.0.2/dist/index.umd.min.js
// @require https://unpkg.com/little-emitter@0.3.5/dist/emitter.js
// @resource api https://pastebin.com/raw/absEYaJ8
// @resource overrides https://pastebin.com/raw/sRQpz471
// @grant GM_addStyle
// @grant GM_deleteValue
// @grant GM_getResourceText
// @grant GM_getValue
// @grant GM_listValues
// @grant GM_registerMenuCommand
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant GM_unregisterMenuCommand
// @connect algolia.net
// @connect www.rottentomatoes.com
// @run-at document-start
// @noframes
// ==/UserScript==
/// <reference types="greasemonkey" />
/// <reference types="tampermonkey" />
/// <reference types="jquery" />
/// <reference types="node" />
/// <reference path="../types/imdb-tomatoes.user.d.ts" />
'use strict';
/* begin */ {
const API_LIMIT = 100
const CHANGE_TARGET = 'target:change'
const DATA_VERSION = 1.3
const DATE_FORMAT = 'YYYY-MM-DD'
const DEBUG_KEY = 'debug'
const DISABLE_CACHE = false
const INACTIVE_MONTHS = 3
const LD_JSON = 'script[type="application/ld+json"]'
const MAX_YEAR_DIFF = 3
const NO_CONSENSUS = 'No consensus yet.'
const NO_MATCH = 'no matching results'
const ONE_DAY = 1000 * 60 * 60 * 24
const ONE_WEEK = ONE_DAY * 7
const RT_BALLOON_CLASS = 'rt-consensus-balloon'
const RT_BASE = 'https://www.rottentomatoes.com'
const RT_WIDGET_CLASS = 'rt-rating'
const STATS_KEY = 'stats'
const TARGET_KEY = 'target'
/** @type {Record<string, number>} */
const METADATA_VERSION = {
[STATS_KEY]: 3,
[TARGET_KEY]: 1,
[DEBUG_KEY]: 1,
}
const BALLOON_OPTIONS = {
classname: RT_BALLOON_CLASS,
css: {
fontFamily: 'Roboto, Helvetica, Arial, sans-serif',
fontSize: '16px',
lineHeight: '24px',
maxWidth: '24rem',
padding: '10px',
},
html: true,
position: 'bottom',
}
const COLOR = {
tbd: '#d9d9d9',
fresh: '#67ad4b',
rotten: '#fb3c3c',
}
const CONNECTION_ERROR = {
status: 420,
statusText: 'Connection Error',
}
const ENABLE_DEBUGGING = JSON.stringify({
data: true,
version: METADATA_VERSION[DEBUG_KEY],
})
const NEW_WINDOW = JSON.stringify({
data: '_blank',
version: METADATA_VERSION[TARGET_KEY],
})
const RT_TYPE = /** @type {const} */ ({
TVSeries: 'tvSeries',
Movie: 'movie',
})
const RT_TYPE_ID = /** @type {const} */ ({
movie: 1,
tvSeries: 2,
})
const STATS = {
requests: 0,
hit: 0,
miss: 0,
preload: {
hit: 0,
miss: 0,
},
}
const UNSHARED = Object.freeze({
got: -1,
want: 1,
max: 0,
})
/**
* an Event Emitter instance used to publish changes to the target for RT links
* ("_blank" or "_self")
*
* @type {import("little-emitter")}
*/
const EMITTER = new exports.Emitter()
/*
* per-page performance metrics, only displayed when debugging is enabled
*/
const PAGE_STATS = { titleComparisons: 0 }
/*
* enable verbose logging
*/
let DEBUG = JSON.parse(GM_getValue(DEBUG_KEY, 'false'))?.data || false
/*
* log a message to the console
*/
const { debug, log, warn } = console
/** @type {(...args: any[]) => void} */
const trace = (...args) => {
if (DEBUG) {
if (args.length === 1 && typeof args[0] === 'function') {
args = [].concat(args[0]())
}
debug(...args)
}
}
/**
* return the Cartesian product of items from a collection of arrays
*
* @type {(arrays: string[][]) => [string, string][]}
*/
const cartesianProduct = exports.enumerator
/**
* deep-clone a JSON-serializable value
*
* @type {<T>(value: T) => T}
*/
const clone = value => JSON.parse(JSON.stringify(value))
/**
* decode HTML entities, e.g.:
*
* from: "Bill & Ted's Excellent Adventure"
* to: "Bill & Ted's Excellent Adventure"
*
* @type {(html: string | undefined) => string}
*/
const htmlDecode = (html) => {
if (!html) {
return ''
}
const el = document.createElement('textarea')
el.innerHTML = html
return el.value
}
/*
* a custom version of get-wild's `get` function which uses a simpler/faster
* path parser since we don't use the extended syntax
*/
const get = exports.getter({ split: '.' })
/**
* retrieve the target for RT links from GM storage, either "_self" (default)
* or "_blank" (new window)
*
* @type {() => LinkTarget}
*/
const getRTLinkTarget = () => JSON.parse(GM_getValue(TARGET_KEY, 'null'))?.data || '_self'
/**
* extract JSON-LD data for the loaded document
*
* used to extract metadata on IMDb and Rotten Tomatoes
*
* @param {Document | HTMLScriptElement} el
* @param {string} id
*/
function jsonLd (el, id) {
const script = el instanceof HTMLScriptElement
? el
: el.querySelector(LD_JSON)
let data
if (script) {
try {
const json = /** @type {string} */ (script.textContent)
data = JSON.parse(json.trim())
} catch (e) {
throw new Error(`Can't parse JSON-LD data for ${id}: ${e}`)
}
} else {
throw new Error(`Can't find JSON-LD data for ${id}`)
}
return data
}
const BaseMatcher = {
/**
* return the consensus from an RT page as a HTML string
*
* @param {RTDoc} $rt
* @return {string}
*/
consensus ($rt) {
return $rt.find('#critics-consensus p').html()
},
/**
* return the last time an RT page was updated based on its most recently
* published review
*
* @param {RTDoc} $rt
* @return {DayJs | undefined}
*/
lastModified ($rt) {
return pluck($rt.meta.review, 'dateCreated')
.map(dayjs)
.sort((a, b) => b.unix() - a.unix())
.shift()
},
rating ($rt) {
const $rating = $rt.find('rt-button[slot="criticsScore"]')
const rating = parseInt($rating.text().trim())
return rating >= 0 ? rating : -1
},
}
const MovieMatcher = {
/**
* return a movie record ({ url: string }) from the API results which
* matches the supplied IMDb data
*
* @param {any} imdb
* @param {RTMovieResult[]} rtResults
*/
match (imdb, rtResults) {
const sharedWithImdb = shared(imdb.cast)
const sorted = rtResults
.flatMap((rt, index) => {
// XXX the order of these tests matters: do fast, efficient
// checks first to reduce the number of results for the more
// expensive checks to process
const { title, vanity: slug } = rt
if (!(title && slug)) {
warn('invalid result:', rt)
return []
}
const rtYear = rt.releaseYear ? Number(rt.releaseYear) : null
const yearDiff = (imdb.year && rtYear)
? { value: Math.abs(imdb.year - rtYear) }
: null
if (yearDiff && yearDiff.value > MAX_YEAR_DIFF) {
return []
}
/** @type {Shared} */
let castMatch = UNSHARED
let verify = true
const rtCast = pluck(rt.cast, 'name')
if (rtCast.length) {
const fullShared = sharedWithImdb(rtCast)
if (fullShared.got >= fullShared.want) {
verify = false
castMatch = fullShared
} else if (fullShared.got) {
// fall back to matching IMDb's main cast (e.g. 2/3) if
// the full-cast match fails (e.g. 8/18)
const mainShared = shared(imdb.mainCast, rtCast)
if (mainShared.got >= mainShared.want) {
verify = false
castMatch = mainShared
castMatch.full = fullShared
} else {
return []
}
} else {
return []
}
}
const rtRating = rt.rottenTomatoes?.criticsScore
const url = `/m/${slug}`
// XXX the title is in the AKA array, but a) we don't want to
// assume that and b) it's not usually first
const rtTitles = rt.aka ? [...new Set([title, ...rt.aka])] : [title]
// XXX only called after the other checks have filtered out
// non-matches, so the number of comparisons remains small
// (usually 1 or 2, and seldom more than 3, even with 100 results)
const titleMatch = titleSimilarity(imdb.titles, rtTitles)
const result = {
title,
url,
year: rtYear,
cast: rtCast,
titleMatch,
castMatch,
yearDiff,
rating: rtRating,
titles: rtTitles,
popularity: rt.pageViews_popularity ?? 0,
updated: rt.updateDate,
index,
verify,
}
return [result]
})
.sort((a, b) => {
// combine the title and the year into a single score
//
// being a year or two out shouldn't be a dealbreaker, and it's
// not uncommon for an RT title to differ from the IMDb title
// (e.g. an AKA), so we don't want one of these to pre-empt the
// other (yet)
const score = new Score()
score.add(b.titleMatch - a.titleMatch)
if (a.yearDiff && b.yearDiff) {
score.add(a.yearDiff.value - b.yearDiff.value)
}
const popularity = (a.popularity && b.popularity)
? b.popularity - a.popularity
: 0
return (b.castMatch.got - a.castMatch.got)
|| (score.b - score.a)
|| (b.titleMatch - a.titleMatch) // prioritise the title if we're still deadlocked
|| popularity // last resort
})
debug('matches:', sorted)
return sorted[0]
},
/**
* return the likely RT path for an IMDb movie title, e.g.:
*
* title: "Bolt"
* path: "/m/bolt"
*
* @param {string} title
*/
rtPath (title) {
return `/m/${rtName(title)}`
},
/**
* confirm the supplied RT page data matches the IMDb metadata
*
* @param {any} imdb
* @param {RTDoc} $rt
* @return {boolean}
*/
verify (imdb, $rt) {
log('verifying movie')
// match the director(s)
const rtDirectors = pluck($rt.meta.director, 'name')
return verifyShared({
name: 'directors',
imdb: imdb.directors,
rt: rtDirectors,
})
},
}
const TVMatcher = {
/**
* return a TV show record ({ url: string }) from the API results which
* matches the supplied IMDb data
*
* @param {any} imdb
* @param {RTTVResult[]} rtResults
*/
match (imdb, rtResults) {
const sharedWithImdb = shared(imdb.cast)
const sorted = rtResults
.flatMap((rt, index) => {
// XXX the order of these tests matters: do fast, efficient
// checks first to reduce the number of results for the more
// expensive checks to process
const { title, vanity: slug } = rt
if (!(title && slug)) {
warn('invalid result:', rt)
return []
}
const startYear = rt.releaseYear ? Number(rt.releaseYear) : null
const startYearDiff = (imdb.startYear && startYear)
? { value: Math.abs(imdb.startYear - startYear) }
: null
if (startYearDiff && startYearDiff.value > MAX_YEAR_DIFF) {
return []
}
const endYear = rt.seriesFinale ? dayjs(rt.seriesFinale).year() : null
const endYearDiff = (imdb.endYear && endYear)
? { value: Math.abs(imdb.endYear - endYear) }
: null
if (endYearDiff && endYearDiff.value > MAX_YEAR_DIFF) {
return []
}
const seasons = rt.seasons || []
const seasonsDiff = (imdb.seasons && seasons.length)
? { value: Math.abs(imdb.seasons - seasons.length) }
: null
/** @type {Shared} */
let castMatch = UNSHARED
let verify = true
const rtCast = pluck(rt.cast, 'name')
if (rtCast.length) {
const fullShared = sharedWithImdb(rtCast)
if (fullShared.got >= fullShared.want) {
verify = false
castMatch = fullShared
} else if (fullShared.got) {
// fall back to matching IMDb's main cast (e.g. 2/3) if
// the full-cast match fails (e.g. 8/18)
const mainShared = shared(imdb.mainCast, rtCast)
if (mainShared.got >= mainShared.want) {
verify = false
castMatch = mainShared
castMatch.full = fullShared
} else {
return []
}
} else {
return []
}
}
const rtRating = rt.rottenTomatoes?.criticsScore
const url = `/tv/${slug}/s01`
// XXX the title is in the AKA array, but a) we don't want to
// assume that and b) it's not usually first
const rtTitles = rt.aka ? [...new Set([title, ...rt.aka])] : [title]
// XXX only called after the other checks have filtered out
// non-matches, so the number of comparisons remains small
// (usually 1 or 2, and seldom more than 3, even with 100 results)
const titleMatch = titleSimilarity(imdb.titles, rtTitles)
const result = {
title,
url,
startYear,
endYear,
seasons: seasons.length,
cast: rtCast,
titleMatch,
castMatch,
startYearDiff,
endYearDiff,
seasonsDiff,
rating: rtRating,
titles: rtTitles,
popularity: rt.pageViews_popularity ?? 0,
index,
updated: rt.updateDate,
verify,
}
return [result]
})
.sort((a, b) => {
const score = new Score()
score.add(b.titleMatch - a.titleMatch)
if (a.startYearDiff && b.startYearDiff) {
score.add(a.startYearDiff.value - b.startYearDiff.value)
}
if (a.endYearDiff && b.endYearDiff) {
score.add(a.endYearDiff.value - b.endYearDiff.value)
}
if (a.seasonsDiff && b.seasonsDiff) {
score.add(a.seasonsDiff.value - b.seasonsDiff.value)
}
const popularity = (a.popularity && b.popularity)
? b.popularity - a.popularity
: 0
return (b.castMatch.got - a.castMatch.got)
|| (score.b - score.a)
|| (b.titleMatch - a.titleMatch) // prioritise the title if we're still deadlocked
|| popularity // last resort
})
debug('matches:', sorted)
return sorted[0] // may be undefined
},
/**
* return the likely RT path for an IMDb TV show title, e.g.:
*
* title: "Sesame Street"
* path: "/tv/sesame_street/s01"
*
* @param {string} title
*/
rtPath (title) {
return `/tv/${rtName(title)}/s01`
},
/**
* confirm the supplied RT page data matches the IMDb data
*
* @param {any} imdb
* @param {RTDoc} $rt
* @return {boolean}
*/
verify (imdb, $rt) {
log('verifying TV show')
// match the genre(s) AND release date
if (!(imdb.genres.length && imdb.releaseDate)) {
return false
}
const rtGenres = ($rt.meta.genre || [])
.flatMap(it => it === 'Mystery & Thriller' ? it.split(' & ') : [it])
if (!rtGenres.length) {
return false
}
const matchedGenres = verifyShared({
name: 'genres',
imdb: imdb.genres,
rt: rtGenres,
})
if (!matchedGenres) {
return false
}
debug('verifying release date')
const startDate = get($rt.meta, 'partOfSeries.startDate')
if (!startDate) {
return false
}
const rtReleaseDate = dayjs(startDate).format(DATE_FORMAT)
debug('imdb release date:', imdb.releaseDate)
debug('rt release date:', rtReleaseDate)
return rtReleaseDate === imdb.releaseDate
}
}
const Matcher = {
tvSeries: TVMatcher,
movie: MovieMatcher,
}
/*
* a helper class used to load and verify data from RT pages which transparently
* handles the selection of the most suitable URL, either from the API (match)
* or guessed from the title (fallback)
*/
class RTClient {
/**
* @param {Object} options
* @param {any} options.match
* @param {Matcher[keyof Matcher]} options.matcher
* @param {any} options.preload
* @param {RTState} options.state
*/
constructor ({ match, matcher, preload, state }) {
this.match = match
this.matcher = matcher
this.preload = preload
this.state = state
}
/**
* transform an XHR response into a JQuery document wrapper with a +meta+
* property containing the page's parsed JSON-LD data
*
* @param {Tampermonkey.Response<any>} res
* @param {string} id
* @return {RTDoc}
*/
_parseResponse (res, id) {
const parser = new DOMParser()
const dom = parser.parseFromString(res.responseText, 'text/html')
const $rt = $(dom)
const meta = jsonLd(dom, id)
return Object.assign($rt, { meta, document: dom })
}
/**
* confirm the metadata of the RT page (match or fallback) matches the IMDb
* data
*
* @param {any} imdb
* @param {RTDoc} rtPage
* @param {boolean} fallbackUnused
* @return {Promise<{ verified: boolean, rtPage: RTDoc }>}
*/
async _verify (imdb, rtPage, fallbackUnused) {
const { match, matcher, preload, state } = this
let verified = matcher.verify(imdb, rtPage)
if (!verified) {
if (match.force) {
log('forced:', true)
verified = true
} else if (fallbackUnused) {
state.url = preload.fullUrl
log('loading fallback URL:', preload.fullUrl)
const res = await preload.request
if (res) {
log(`fallback response: ${res.status} ${res.statusText}`)
rtPage = this._parseResponse(res, preload.url)
verified = matcher.verify(imdb, rtPage)
} else {
log(`error loading ${preload.fullUrl} (${preload.error.status} ${preload.error.statusText})`)
}
}
}
log('verified:', verified)
return { verified, rtPage }
}
/**
* load the RT URL (match or fallback) and return the resulting RT page
*
* @param {any} imdb
* @return {Promise<RTDoc | void>}
*/
async loadPage (imdb) {
const { match, preload, state } = this
let requestType = match.fallback ? 'fallback' : 'match'
let verify = match.verify
let fallbackUnused = false
let res
log(`loading ${requestType} URL:`, state.url)
// match URL (API result) and fallback URL (guessed) are the same
if (match.url === preload.url) {
res = await preload.request // join the in-flight request
} else { // different match URL and fallback URL
try {
res = await asyncGet(state.url) // load the (absolute) match URL
fallbackUnused = true // only set if the request succeeds
} catch (error) { // bogus URL in API result (or transient server error)
log(`error loading ${state.url} (${error.status} ${error.statusText})`)
if (match.force) { // URL locked in checkOverrides, so nothing to fall back to
return
} else { // use (and verify) the fallback URL
requestType = 'fallback'
state.url = preload.fullUrl
verify = true
log(`loading ${requestType} URL:`, state.url)
res = await preload.request
}
}
}
if (!res) {
log(`error loading ${state.url} (${preload.error.status} ${preload.error.statusText})`)
return
}
log(`${requestType} response: ${res.status} ${res.statusText}`)
let rtPage = this._parseResponse(res, state.url)
if (verify) {
const { verified, rtPage: newRtPage } = await this._verify(
imdb,
rtPage,
fallbackUnused
)
if (!verified) {
return
}
rtPage = newRtPage
}
return rtPage
}
}
/*
* a helper class which keeps a running total of scores for two values (a and
* b). used to rank values in a sort function
*/
class Score {
constructor () {
this.a = 0
this.b = 0
}
/**
* add a score to the total
*
* @param {number} order
* @param {number=} points
*/
add (order, points = 1) {
if (order < 0) {
this.a += points
} else if (order > 0) {
this.b += points
}
}
}
/******************************************************************************/
/**
* raise a non-error exception indicating no matching result has been found
*
* @param {string} message
*/
// XXX return an error object rather than throwing it to work around a
// TypeScript bug: https://github.com/microsoft/TypeScript/issues/31329
function abort (message = NO_MATCH) {
return Object.assign(new Error(message), { abort: true })
}
/**
* add Rotten Tomatoes widgets to the desktop/mobile ratings bars
*
* @param {Object} data
* @param {string} data.url
* @param {string} data.consensus
* @param {number} data.rating
*/
async function addWidgets ({ consensus, rating, url }) {
trace('adding RT widgets')
const imdbRatings = await waitFor('IMDb widgets', () => {
/** @type {NodeListOf<HTMLElement>} */
const ratings = document.querySelectorAll('[data-testid="hero-rating-bar__aggregate-rating"]')
return ratings.length > 1 ? ratings : null
})
trace('found IMDb widgets')
const balloonOptions = Object.assign({}, BALLOON_OPTIONS, { contents: consensus })
const score = rating === -1 ? 'N/A' : `${rating}%`
const rtLinkTarget = getRTLinkTarget()
/** @type {"tbd" | "rotten" | "fresh"} */
let style
if (rating === -1) {
style = 'tbd'
} else if (rating < 60) {
style = 'rotten'
} else {
style = 'fresh'
}
// add a custom stylesheet which:
//
// - sets the star (SVG) to the right color
// - reorders the appended widget (see attachWidget)
// - restores support for italics in the consensus text
GM_addStyle(`
.${RT_WIDGET_CLASS} svg { color: ${COLOR[style]}; }
.${RT_WIDGET_CLASS} { order: -1; }
.${RT_BALLOON_CLASS} em { font-style: italic; }
`)
// the markup for the small (e.g. mobile) and large (e.g. desktop) IMDb
// ratings widgets is exactly the same - they only differ in the way they're
// (externally) styled
for (const imdbRating of imdbRatings) {
const $imdbRating = $(imdbRating)
const $ratings = $imdbRating.parent()
// clone the IMDb rating widget
const $rtRating = $imdbRating.clone()
// 1) assign a unique class for styling
$rtRating.addClass(RT_WIDGET_CLASS)
// 2) replace "IMDb Rating" with "RT Rating"
$rtRating.children().first().text('RT RATING')
// 3) remove the review count and its preceding spacer element
const $score = $rtRating.find('[data-testid="hero-rating-bar__aggregate-rating__score"]')
$score.nextAll().remove()
// 4) replace the IMDb rating with the RT score and remove the "/ 10" suffix
$score.children().first().text(score).nextAll().remove()
// 5) rename the testids, e.g.:
// hero-rating-bar__aggregate-rating -> hero-rating-bar__rt-rating
$rtRating.find('[data-testid]').addBack().each((_index, el) => {
$(el).attr('data-testid', (_index, id) => id.replace('aggregate', 'rt'))
})
// 6) update the link's label and URL
const $link = $rtRating.find('a[href]')
$link.attr({ 'aria-label': 'View RT Rating', href: url, target: rtLinkTarget })
// 7) observe changes to the link's target
EMITTER.on(CHANGE_TARGET, (/** @type {LinkTarget} */ target) => $link.prop('target', target))
// 8) attach the tooltip to the widget
$rtRating.balloon(balloonOptions)
// 9) prepend the widget to the ratings bar
attachWidget($ratings.get(0), $rtRating.get(0))
}
trace('added RT widgets')
}
/**
* promisified cross-origin HTTP requests
*
* @param {string} url
* @param {AsyncGetOptions} [options]
*/
function asyncGet (url, options = {}) {
if (options.params) {
url = url + '?' + $.param(options.params)
}
const id = options.title || url
const request = Object.assign({ method: 'GET', url }, options.request || {})
return new Promise((resolve, reject) => {
request.onload = res => {
if (res.status >= 400) {
const error = Object.assign(
new Error(`error fetching ${id} (${res.status} ${res.statusText})`),
{ status: res.status, statusText: res.statusText }
)
reject(error)
} else {
resolve(res)
}
}
// XXX apart from +finalUrl+, the +onerror+ response object doesn't
// contain any useful info
request.onerror = _res => {
const { status, statusText } = CONNECTION_ERROR
const error = Object.assign(
new Error(`error fetching ${id} (${status} ${statusText})`),
{ status, statusText },
)
reject(error)
}
GM_xmlhttpRequest(request)
})
}
/**
* attach an RT ratings widget to a ratings bar
*
* although the widget appears to be prepended to the bar, we need to append it
* (and reorder it via CSS) to work around React reconciliation (updating the
* DOM to match the (virtual DOM representation of the) underlying model) after
* we've added the RT widget
*
* when this synchronisation occurs, React will try to restore nodes
* (attributes, text, elements) within each widget to match the widget's props,
* so the first widget will be updated in place to match the data for the IMDb
* rating etc. this changes some, but not all nodes within an element, and most
* attributes added to/changed in a prepended RT widget remain when it's
* reverted back to an IMDb widget, including its class (rt-rating), which
* controls the color of the rating star. as a result, we end up with a restored
* IMDb widget but with an RT-colored star (and with the RT widget removed since
* it's not in the ratings-bar model)
*
* if we *append* the RT widget, none of the other widgets will need to be
* changed/updated if the DOM is re-synced, so we won't end up with a mangled
* IMDb widget; however, our RT widget will still be removed since it's not in
* the model. to rectify this, we use a mutation observer to detect and revert
* its removal (which happens no more than once - the ratings bar is frozen
* (i.e. synchronisation is halted) once the page has loaded)
*
* @param {HTMLElement | undefined} target
* @param {HTMLElement | undefined} rtRating
*/
function attachWidget (target, rtRating) {
if (!target) {
throw new ReferenceError("can't find ratings bar")
}
if (!rtRating) {
throw new ReferenceError("can't find RT widget")
}
const init = { childList: true }
// restore the RT widget if it is removed. only called (once) if the widget
// is added "quickly" (i.e. while the ratings bar is still being finalized),
// e.g. when the result is cached
const checkRatingsWidget = () => {
if (rtRating.parentElement !== target) {
observer.disconnect()
target.appendChild(rtRating)
observer.observe(target, init)
}
}