-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
GeniusLyrics.js
4640 lines (4232 loc) · 213 KB
/
GeniusLyrics.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==
// @exclude *
// ==UserLibrary==
// @name GeniusLyrics
// @description Downloads and shows genius lyrics for Tampermonkey scripts
// @version 5.16.8
// @license GPL-3.0-or-later; http://www.gnu.org/licenses/gpl-3.0.txt
// @copyright 2019, cuzi ([email protected]) and contributors
// @supportURL https://github.com/cvzi/genius-lyrics-userscript/issues
// @icon https://avatars.githubusercontent.com/u/2738430?s=200&v=4
// ==/UserLibrary==
// @homepageURL https://github.com/cvzi/genius-lyrics-userscript
// ==/UserScript==
/*
Copyright (C) 2019, cuzi ([email protected]) and contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/*
This library requires the following permission in the userscript:
* grant GM.xmlHttpRequest
* grant GM.getValue
* grant GM.setValue
* connect genius.com
*/
/* global Blob, top, HTMLElement, GM_openInTab, crypto, Document */
/* jshint asi: true, esversion: 8 */
if (typeof module !== 'undefined') {
module.exports = geniusLyrics
}
function geniusLyrics (custom) { // eslint-disable-line no-unused-vars
'use strict'
const __SELECTION_CACHE_VERSION__ = 10
const __REQUEST_CACHE_VERSION__ = 10
/** @type {globalThis.PromiseConstructor} */
const Promise = (async () => { })().constructor // YouTube polyfill to Promise in older browsers will make the feature being unstable.
if (typeof custom !== 'object') {
if (typeof window !== 'undefined') window.alert('geniusLyrics requires options argument')
throw new Error('geniusLyrics requires options argument')
}
let _shouldUseLZStringCompression = null
const testUseLZStringCompression = async () => {
if (typeof _shouldUseLZStringCompression === 'boolean') return _shouldUseLZStringCompression
let res = false
const isLZStringAvailable = typeof LZString !== 'undefined' && typeof (LZString || 0).compressToUTF16 === 'function' // eslint-disable-line no-undef
if (isLZStringAvailable && typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
try {
// Browser 2022+
let isEdge = false
if (typeof webkitCancelAnimationFrame === 'function' && typeof navigator?.userAgentData === 'object') {
// Brave, Chrome, Edge (Browser 2022+)
isEdge = (navigator.userAgentData?.brands?.find(e => e.brand.includes('Edge')) || false)
} else {
// Safari, Firefox
}
if (!isEdge) {
const testFn = async () => {
await Promise.resolve()
const t = crypto.randomUUID()
const r = LZString.decompressFromUTF16(LZString.compressToUTF16(t)) === t // eslint-disable-line no-undef
await Promise.resolve()
return r
}
const r = await Promise.race([testFn().catch(() => { }), new Promise(resolve => (AbortSignal.timeout(9).onabort = resolve))])
res = (r === true)
}
} catch (e) { }
}
return (_shouldUseLZStringCompression = res)
}
const elmBuild = (tag, ...contents) => {
/** @type {HTMLElement} */
const elm = typeof tag === 'string' ? document.createElement(tag) : tag
for (const content of contents) {
if (!content || typeof content !== 'object' || (content instanceof Node)) { // eslint-disable-line no-undef
elm.append(content)
} else if (content.length > 0) {
elm.appendChild(elmBuild(...content))
} else if (content.style) {
Object.assign(elm.style, content.style)
} else if (content.classList) {
elm.classList.add(...content.classList)
} else if (content.attr) {
for (const [attr, val] of Object.entries(content.attr)) elm.setAttribute(attr, val)
} else if (content.listener) {
for (const [attr, val] of Object.entries(content.listener)) elm.addEventListener(attr, val)
} else {
Object.assign(elm, content)
}
}
return elm
}
Array.prototype.forEach.call([
'GM',
'scriptName',
'domain',
'emptyURL',
'listSongs',
'showSearchField',
'addLyrics', // addLyrics would not immediately add lyrics panel
'hideLyrics', // hideLyrics immediately hide lyrics panel
'getCleanLyricsContainer',
'setFrameDimensions'
], function (valName) {
if (!(valName in custom)) {
if (typeof window !== 'undefined') window.alert(`geniusLyrics requires parameter ${valName}`)
throw new Error(`geniusLyrics() requires parameter ${valName}`)
}
})
function unScroll () { // unable to do delete window.xxx
// only for mainWin
window.lastScrollTopPosition = null
window.scrollLyricsBusy = false
window.staticOffsetTop = null
window.latestScrollPos = null
window.newScrollTopPosition = null
window.isPageAbleForAutoScroll = null
}
function hideLyricsWithMessage () {
const ret = custom.hideLyrics(...arguments)
if (ret === false) { // cancelled
return false
}
unScroll()
window.postMessage({ iAm: custom.scriptName, type: 'lyricsDisplayState', visibility: 'hidden' }, '*')
return ret
}
function cancelLoading () {
window.postMessage({ iAm: custom.scriptName, type: 'cancelLoading' }, '*')
}
function getUnmodifiedWindowMethods (win) {
if (!(win instanceof win.constructor)) { // window in isolated context
return win
}
let removeIframeFn = null
let fc = win
try {
const frameId = 'vanillajs-iframe-v1'
let frame = document.getElementById(frameId)
if (!frame) {
frame = document.createElement('iframe')
frame.id = frameId
const blobURL = typeof webkitCancelAnimationFrame === 'function' && typeof kagi === 'undefined' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null // avoid Brave Crash
frame.sandbox = 'allow-same-origin' // script cannot be run inside iframe but API can be obtained from iframe
let n = document.createElement('noscript') // wrap into NOSCRPIT to avoid reflow (layouting)
n.appendChild(frame)
const root = document.documentElement
if (root) {
root.appendChild(n)
if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL))
removeIframeFn = (setTimeout) => {
const removeIframeOnDocumentReady = (e) => {
e && win.removeEventListener('DOMContentLoaded', removeIframeOnDocumentReady, false)
e = n
n = win = removeIframeFn = 0
setTimeout ? setTimeout(() => e.remove(), 200) : e.remove()
}
if (!setTimeout || document.readyState !== 'loading') {
removeIframeOnDocumentReady()
} else {
win.addEventListener('DOMContentLoaded', removeIframeOnDocumentReady, false)
}
}
}
}
fc = (frame ? frame.contentWindow : null) || win
} catch (e) {
console.warn(e)
}
try {
const { requestAnimationFrame, setTimeout, setInterval, clearTimeout, clearInterval } = fc
const res = { requestAnimationFrame, setTimeout, setInterval, clearTimeout, clearInterval }
for (const k in res) res[k] = res[k].bind(win) // necessary
if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn)
return res
} catch (e) {
if (removeIframeFn) removeIframeFn()
throw e
}
}
const { requestAnimationFrame, setTimeout, setInterval, clearTimeout, clearInterval } = getUnmodifiedWindowMethods(window)
const genius = {
option: {
autoShow: true,
themeKey: null,
romajiPriority: 'low',
fontSize: 0, // == 0 : use default value, >= 1 : "px" value
useLZCompression: false,
shouldUseLZStringCompression: null,
cacheHTMLRequest: true, // be careful of cache size if trimHTMLReponseText is false; around 50KB per lyrics including selection cache
requestCallbackResponseTextOnly: true, // default true; just need the request text
enableStyleSubstitution: false, // default false; some checking are provided but not guaranteed
normalizeClassV2: false, // default false; true to add normalized class names (v2)
removeEmptyBlocks: true, // remove elements without content (empty elements with min-height would cause a empty block on the page)
trimHTMLReponseText: true, // make html request to be smaller for caching and window messaging; safe to enable
defaultPlaceholder: 'Search genius.com...' // placeholder for input field
},
f: {
metricPrefix,
cleanUpSongTitle,
showLyrics,
showLyricsAndRemember,
reloadCurrentLyrics,
loadLyrics,
hideLyricsWithMessage,
cancelLoading,
rememberLyricsSelection,
isGreasemonkey,
forgetLyricsSelection,
forgetCurrentLyricsSelection,
getLyricsSelection,
geniusSearch,
searchByQuery,
updateAutoScrollEnabled,
isScrollLyricsEnabled, // refer to user setting
isScrollLyricsCallable, // refer to content rendering
scrollLyrics,
config,
modalAlert,
modalConfirm,
closeModalUIs
},
current: { // store the title and artists of the current lyrics [cached and able to reload]
title: '', // these shall be replaced by CompoundTitle
artists: '', // these shall be replaced by CompoundTitle
compoundTitle: '',
themeSettings: null // currently displayed theme + fontSize
},
iv: {
main: null // unless setupMain is provided and the interval / looping is controlled externally
},
style: {
enabled: false // true to make the iframe content more compact and concise; [only work on Genius Default Theme?]
},
styleProps: { // if style.enabled, feed the content style into styleProps
},
minimizeHit: { // minimize the hit for smaller caches; default all false
noImageURL: false,
noFeaturedArtists: false,
simpleReleaseDate: false,
noRawReleaseDate: false,
shortenArtistName: false,
fixArtistName: false,
removeStats: false, // note: true for YoutubeGeniusLyrics only; as YoutubeGeniusLyrics will not show this info
noRelatedLinks: false,
onlyCompleteLyrics: false
},
onThemeChanged: [],
debug: false
}
function cleanRequestCache () {
return {
__VERSION__: __REQUEST_CACHE_VERSION__
}
}
function cleanSelectionCache () {
return {
__VERSION__: __SELECTION_CACHE_VERSION__
}
}
let askedToSolveCaptcha = false
let loadingFailed = false
let requestCache = cleanRequestCache()
let selectionCache = cleanSelectionCache()
let theme
let annotationsEnabled = true
let autoScrollEnabled = false
const onMessage = {}
const isLZStringAvailable = typeof LZString !== 'undefined' && typeof (LZString || 0).compressToUTF16 === 'function' // eslint-disable-line no-undef
// if (!isLZStringAvailable) throw new Error('LZString is not available. Please update your script.')
async function setJV (key, text) {
if (isLZStringAvailable && genius.option.useLZCompression && genius.option.shouldUseLZStringCompression) {
if (typeof text === 'object') text = JSON.stringify(text)
if (typeof text !== 'string') return null
const z = 'b\n' + LZString.compressToUTF16(text) // eslint-disable-line no-undef
return await custom.GM.setValue(key, z)
} else {
if (typeof text === 'object') text = JSON.stringify(text)
if (typeof text !== 'string') return null
const z = 'a\n' + text
return await custom.GM.setValue(key, z)
}
}
async function getJVstr (key, d) {
const z = await custom.GM.getValue(key, null)
if (z === null) return d
if (z === '{}') return z
if (typeof z !== 'string') return z
const j = z.indexOf('\n')
if (j <= 0) return z
const w = z.substring(0, j)
const t = z.substring(j + 1)
if (w === 'b') return LZString.decompressFromUTF16(t) // eslint-disable-line no-undef
if (w === 'a') return t
return t
}
/*
async function getJVobj (key, d) {
const z = await custom.GM.getValue(key, null)
if (z === null) return d
if (z === '{}') return {}
const t = LZString.decompressFromUTF16(z)
return JSON.parse(t)
}
*/
function measurePlainTextLength (text) {
try {
return (new TextEncoder().encode(text)).length
} catch (e) {
return text.length
}
}
function measureJVLength (obj) {
let z
if (isLZStringAvailable && genius.option.useLZCompression && genius.option.shouldUseLZStringCompression) {
z = LZString.compressToUTF16(JSON.stringify(obj)) // eslint-disable-line no-undef
} else {
z = JSON.stringify(obj)
}
return measurePlainTextLength(z)
}
function getHostname (url) {
// absolute path
if (typeof url === 'string' && url.startsWith('http')) {
const query = new URL(url)
return query.hostname
}
// relative path - use <a> or new URL(url, document.baseURI)
const a = document.createElement('a')
a.href = url
return a.hostname
}
function removeIfExists (e) {
if (e && e.remove) {
e.remove()
}
}
const removeElements = (typeof window.DocumentFragment.prototype.append === 'function')
? function (elements) {
document.createDocumentFragment().append(...elements)
}
: function (elements) {
for (const element of elements) {
element.remove()
}
}
function removeTagsKeepText (node) {
let tmpNode = null
while ((tmpNode = node.firstChild) !== null) {
if ('tagName' in tmpNode && tmpNode.tagName !== 'BR') {
removeTagsKeepText(tmpNode)
} else {
node.parentNode.insertBefore(tmpNode, node)
}
}
node.remove()
}
function decodeHTML (s) {
return `${s}`.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
}
function metricPrefix (n, decimals, k) {
// http://stackoverflow.com/a/18650828
if (n <= 0) {
return String(n)
}
k = k || 1000
const dm = decimals <= 0 ? 0 : decimals || 2
const sizes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
const i = Math.floor(Math.log(n) / Math.log(k))
return parseFloat((n / Math.pow(k, i)).toFixed(dm)) + sizes[i]
}
function cleanUpSongTitle (songTitle) {
// Remove featuring artists and version info from song title
songTitle = songTitle.replace(/\((single|master|studio|stereo|mono|anniversary|digital|edit|edition|naked|original|re|ed|no.*?\d+|mix|version|\d+th|\d{4}|\s|\.|-|\/)+\)/i, '').trim()
songTitle = songTitle.replace(/[-‧⋅·ᐧ•‐‒–—―﹘]\s*(single|master|studio|stereo|mono|anniversary|digital|edit|edition|naked|original|re|ed|no.*?\d+|mix|version|\d+th|\d{4}|\s|\.|-|\/)+/i, '').trim()
songTitle = songTitle.replace(/fe?a?t\.?u?r?i?n?g?\s+[^)]+/i, '')
songTitle = songTitle.replace(/\(\s*\)/, ' ').replace('"', ' ').replace('[', ' ').replace(']', ' ').replace('|', ' ')
songTitle = songTitle.replace(/\s\s+/, ' ')
songTitle = songTitle.replace(/[\u200B-\u200D\uFEFF]/g, '') // zero width spaces
songTitle = songTitle.trim()
return songTitle
}
function sumOffsets (obj) {
const sums = { left: 0, top: 0 }
while (obj) {
sums.left += obj.offsetLeft
sums.top += obj.offsetTop
obj = obj.offsetParent
}
return sums
}
function convertSelectionCacheV0toV1 (selectionCache) {
// the old cache key use '--' which is possible to mixed up with the brand name
// the new cache key use '\t' as separator
const ret = {}
const bugKeys = []
function pushBugKey (selectionCacheKey) {
const s = selectionCacheKey.split(/\t/)
if (s.length !== 2) return
const songTitle = s[0]
const artists = s[1]
// setting simpleTitle as cache key was a bug
const simpleTitle = songTitle.replace(/\s*-\s*.+?$/, '') // Remove anything following the last dash
if (simpleTitle !== songTitle) {
bugKeys.push(`${simpleTitle}\t${artists}`)
}
}
console.warn('Genius Lyrics - old section cache V0 is found: ', selectionCache)
for (const originalKey in selectionCache) {
if (originalKey === '__VERSION__') continue
let k = 0
const selectionCacheKey = originalKey
.replace(/[\r\n\t\s]+/g, ' ')
.replace(/--/g, () => {
k++
return '\t'
})
if (k === 1) {
pushBugKey(selectionCacheKey)
ret[selectionCacheKey] = selectionCache[originalKey]
}
}
for (const bugKey of bugKeys) {
delete ret[bugKey]
}
console.warn('Genius Lyrics - old section cache V0 is converted to V1: ', ret)
return ret
}
function convertSelectionCacheV1toV2 (selectionCache) {
// ${title}\t${artists} => ${artists}\t${title}
const ret = {}
console.warn('Genius Lyrics - old section cache V1 is found: ', selectionCache)
for (const originalKey in selectionCache) {
if (originalKey === '__VERSION__') continue
const s = originalKey.split('\t')
const selectionCacheKey = `${s[1]}\t${s[0]}`
ret[selectionCacheKey] = selectionCache[originalKey]
}
console.warn('Genius Lyrics - old section cache V1 is converted to V2: ', ret)
return ret
}
function loadRequestCache (storedValue) {
// global requestCache
if (storedValue === '{}') {
requestCache = cleanRequestCache()
} else {
try {
requestCache = JSON.parse(storedValue)
if (!requestCache.__VERSION__) {
requestCache.__VERSION__ = 0
}
} catch (e) {
requestCache = cleanRequestCache()
}
}
if (requestCache.__VERSION__ !== __REQUEST_CACHE_VERSION__) {
requestCache = cleanRequestCache()
setJV('requestcache', requestCache)
}
}
function loadSelectionCache (storedValue) {
// global selectionCache
if (storedValue === '{}') {
selectionCache = cleanSelectionCache()
} else {
try {
selectionCache = JSON.parse(storedValue)
if (!selectionCache.__VERSION__) {
selectionCache.__VERSION__ = 0
}
} catch (e) {
selectionCache = cleanSelectionCache()
}
}
if (selectionCache.__VERSION__ !== __SELECTION_CACHE_VERSION__) {
if (selectionCache.__VERSION__ === 0) {
selectionCache = convertSelectionCacheV0toV1(selectionCache)
selectionCache.__VERSION__ = 1
selectionCache = convertSelectionCacheV1toV2(selectionCache)
selectionCache.__VERSION__ = __SELECTION_CACHE_VERSION__
} else if (selectionCache.__VERSION__ === 1) {
selectionCache = convertSelectionCacheV1toV2(selectionCache)
selectionCache.__VERSION__ = __SELECTION_CACHE_VERSION__
} else {
selectionCache = cleanSelectionCache()
}
setJV('selectioncache', selectionCache)
}
}
function loadCache () {
Promise.all([
getJVstr('selectioncache', '{}'),
getJVstr('requestcache', '{}'),
custom.GM.getValue('optionautoshow', true)
]).then(function (values) {
loadSelectionCache(values[0])
loadRequestCache(values[1])
genius.option.autoShow = values[2] === true || values[2] === 'true'
/*
requestCache = {
"cachekey0": "121648565.5\njsondata123",
...
}
*/
const now = (new Date()).getTime()
const exp = 2 * 60 * 60 * 1000
for (const prop in requestCache) {
if (prop === '__VERSION__') continue
// Delete cached values, that are older than 2 hours
const time = requestCache[prop].split('\n')[0]
if ((now - (new Date(time)).getTime()) > exp) {
delete requestCache[prop]
}
}
})
}
function invalidateRequestCache (obj) {
const resultCachekey = JSON.stringify(obj)
if (resultCachekey in requestCache) {
delete requestCache[resultCachekey]
}
}
function getRequestCacheKeyReplacer (key, value) {
if (key === 'headers') {
return undefined
} else if (key === 'url') {
if (typeof value !== 'string') return undefined
let idx
idx = value.lastIndexOf('/')
value = `~${idx}${value.substring(idx)}`
idx = value.indexOf('?')
if (idx > 0) {
value = value.substring(0, idx + 1) + decodeURIComponent(value.substring(idx + 1)).replace(/\s+/g, '-')
}
}
return value
}
function getRequestCacheKey (obj) {
return JSON.stringify(obj, getRequestCacheKeyReplacer)
}
function request (obj) {
const cachekey = getRequestCacheKey(obj)
if (cachekey in requestCache) {
return obj.load(JSON.parse(requestCache[cachekey].split('\n')[1]), null)
}
const method = obj.method ? obj.method : 'GET'
let headers = {
Referer: obj.url,
// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
Host: getHostname(obj.url),
'User-Agent': navigator.userAgent
}
if (method === 'POST') headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
if (obj.responseType === 'json') headers['Accept'] = 'application/json' // eslint-disable-line dot-notation
if (obj.headers) {
headers = Object.assign(headers, obj.headers)
}
const cookiePartition = {}
if (obj.url.startsWith('https://genius.com/')) {
cookiePartition.topLevelSite = 'https://genius.com'
}
const req = {
url: obj.url,
method,
data: obj.data,
headers,
cookiePartition,
onerror: obj.error ? obj.error : function xmlHttpRequestGenericOnError (response) { console.error('xmlHttpRequestGenericOnError: ' + response) },
onload: function xmlHttpRequestOnLoad (response) {
const time = (new Date()).toJSON()
let cacheObject = null
if (typeof obj.preProcess === 'function') {
const proceed = obj.preProcess.call(this, response)
if (typeof proceed === 'object') {
cacheObject = proceed
}
}
if (cacheObject === null) {
// only if preProcess is undefined or preProcess() does not return a object
if (genius.option.requestCallbackResponseTextOnly === true) {
// only cache responseText
cacheObject = { responseText: response.responseText }
} else {
// full object
const newObject = Object.assign({}, response)
newObject.responseText = response.responseText // key 'responseText' is not enumerable
cacheObject = newObject
}
}
// only cache when the callback call this function
function cacheResult (cacheObject) {
if (cacheObject !== null) {
requestCache[cachekey] = time + '\n' + JSON.stringify(cacheObject)
setJV('requestcache', requestCache)
}
}
obj.load(cacheObject, cacheResult)
}
}
if (obj.responseType) req.responseType = obj.responseType
if (obj.responseType === 'json') req.overrideMimeType = 'application/json; charset=utf-8'
return custom.GM.xmlHttpRequest(req)
}
function generateCompoundTitle (title, artists) {
title = title.replace(/\s+/g, ' ') // space, \n, \t, ...
artists = artists.replace(/\s+/g, ' ')
return `${artists}\t${title}`
}
function displayTextOfCompoundTitle (compoundTitle) {
return compoundTitle.replace('\t', ' ')
}
function rememberLyricsSelection (title, artists, jsonHit) {
const compoundTitleKey = artists === null ? title : generateCompoundTitle(title, artists)
if (typeof jsonHit === 'object') {
jsonHit = JSON.stringify(jsonHit)
}
if (typeof jsonHit !== 'string') {
return
}
selectionCache[compoundTitleKey] = jsonHit
setJV('selectioncache', selectionCache)
}
function forgetLyricsSelection (title, artists) {
const compoundTitleKey = artists === null ? title : generateCompoundTitle(title, artists)
if (compoundTitleKey in selectionCache) {
delete selectionCache[compoundTitleKey]
setJV('selectioncache', selectionCache)
}
}
function forgetCurrentLyricsSelection () {
const ctitle = genius.current.compoundTitle
if (typeof ctitle === 'string') {
forgetLyricsSelection(ctitle, null)
return true
}
return false
}
function getLyricsSelection (title, artists) {
const compoundTitleKey = artists === null ? title : generateCompoundTitle(title, artists)
if (compoundTitleKey in selectionCache) {
return JSON.parse(selectionCache[compoundTitleKey])
} else {
return false
}
}
function ReleaseDateComponent (components) {
if (!components) return
if (components.year - components.month - components.day > 0) { // avoid NaN
return `${components.year}.${components.month < 10 ? '0' : ''}${components.month}.${components.day < 10 ? '0' : ''}${components.day}`
}
return null
}
function removeSymbolsAndWhitespace (s) {
return s.replace(/[\s\p{P}$+<=>^`|~]/gu, '')
}
function getHitResultType (result) {
if (typeof (result.language || 0) === 'string') {
if (result.language === 'romanization') return 'romanization'
if (result.language === 'romanisation') return 'romanization'
if (result.language === 'translation') return 'translation'
}
const primaryArtist = result.primary_artist || 0
if (primaryArtist) {
if (typeof primaryArtist.slug === 'string' && (primaryArtist.slug || '').startsWith('Genius-')) {
if (/Genius-[Rr]omani[zs]ations?/.test(primaryArtist.slug)) {
return 'romanization'
}
if (/Genius-[Tt]ranslations?/.test(primaryArtist.slug)) {
return 'translation'
}
}
if (typeof primaryArtist.name === 'string' && (primaryArtist.name || '').startsWith('Genius')) {
if (/Genius\s+[Rr]omani[zs]ations?/.test(primaryArtist.name)) {
return 'romanization'
}
if (/Genius\s+[Tt]ranslations?/.test(primaryArtist.name)) {
return 'translation'
}
}
}
const path = result.path || 0
if (typeof path === 'string') {
if (/\b[Gg]enius\b\S+\bromani[zs]ations?\b/.test(path)) return 'romanization'
if (/\b[Gg]enius\b\S+\btranslations?\b/.test(path)) return 'translation'
}
return ''
}
function modifyHits (hits, query) {
// the original hits store too much and not in a proper ordering
// only song.result.url is neccessary
// There are few instrumental music existing in Genius
// No lyrics will be provided for instrumental music in Genius
hits = hits.filter(hit => {
if (hit.result.instrumental === true) return false
if (hit.result.lyrics_state === 'unreleased') return false
if (genius.minimizeHit.onlyCompleteLyrics === true && hit.result.lyrics_state !== 'complete') return false
const primary_artist = (hit.result.primary_artist || 0).name || 0 // eslint-disable-line camelcase
if (primary_artist.startsWith('Deleted') && primary_artist.endsWith('Artist')) return false // eslint-disable-line camelcase
return true
})
const removeZeroWidthSpaceAndTrimStringsInObject = function (obj) {
// Recursively traverse object, and remove zero width spaces and trim string values
if (obj !== null && typeof obj === 'object') {
Object.entries(obj).forEach(([key, value]) => {
obj[key] = removeZeroWidthSpaceAndTrimStringsInObject(value)
})
} else if (typeof obj === 'string') {
return obj.replace(/[\u200B-\u200D\uFEFF]/g, '').trim()
}
return obj
}
for (const hit of hits) {
const result = hit.result
if (!result) return
const primaryArtist = result.primary_artist || 0
const minimizeHit = genius.minimizeHit
const hitResultType = getHitResultType(hit.result)
delete hit.highlights // always []
delete result.annotation_count // always 0
delete result.pyongs_count // always null
if (minimizeHit.noImageURL) {
// if the script does not require the images, remove to save storage
delete result.header_image_thumbnail_url
delete result.header_image_url
delete result.song_art_image_thumbnail_url
delete result.song_art_image_url
}
if (minimizeHit.noRelatedLinks) {
delete result.relationships_index_url
}
if (minimizeHit.noFeaturedArtists) {
// it can be a band of 35 peoples which is wasting storage
delete result.featured_artists
}
if (primaryArtist) {
if (minimizeHit.noImageURL) {
delete primaryArtist.header_image_url
delete primaryArtist.image_url
}
if (minimizeHit.noRelatedLinks) {
delete primaryArtist.api_path
delete primaryArtist.url
delete primaryArtist.is_meme_verified
delete primaryArtist.is_verified
delete primaryArtist.index_character
delete primaryArtist.slug
}
}
// reduce release date storage
if (minimizeHit.simpleReleaseDate && 'release_date_components' in result) {
const c = ReleaseDateComponent(result.release_date_components)
if (c !== null) {
result.release_date = c
}
}
if (minimizeHit.noRawReleaseDate) {
delete result.release_date_components
delete result.release_date_for_display
delete result.release_date_with_abbreviated_month_for_display
}
if (minimizeHit.shortenArtistName && primaryArtist && typeof primaryArtist.name === 'string' && typeof result.artist_names === 'string') {
// if it is a brand the title could be very long as it compose it with the full member names
if (primaryArtist.name.length < result.artist_names.length) {
result.artist_names = primaryArtist.name
}
}
if (minimizeHit.fixArtistName) {
if (hitResultType === 'romanization' && result.title === result.title_with_featured && result.artist_names === primaryArtist.name) {
// Example: "なとり (Natori) - Overdose (Romanized)"
const split = result.title.split(' - ')
if (split.length === 2) {
result.artist_names = split[0]
primaryArtist.name = split[0]
result.title = split[1]
result.title_with_featured = split[1]
}
}
}
if (minimizeHit.removeStats) {
delete result.stats
}
// Remove zero width spaces in strings and trim strings
removeZeroWidthSpaceAndTrimStringsInObject(result)
if (hits.length > 1) {
if (hit.type === 'song') {
hit._order = 2600
} else {
hit._order = 1300
}
if (hitResultType === 'romanization') {
if (genius.option.romajiPriority === 'low') {
hit._order -= 50
} else if (genius.option.romajiPriority === 'high') {
hit._order += 50
}
}
if (hit.result.updated_by_human_at) {
hit._order += 400
}
if (hitResultType === 'translation') {
// possible translation for non-english songs
// if all results are en, no different for hit._order reduction
hit._order -= 1000
}
// Sort hits by comparing to the query
if (query) {
query = query.toLowerCase()
const queryNoSymbols = removeSymbolsAndWhitespace(query)
const title = result.title.toLowerCase()
const artist = primaryArtist ? primaryArtist.name.toLowerCase() : ''
const titleNoSymbols = removeSymbolsAndWhitespace(title)
const artistNoSymbols = removeSymbolsAndWhitespace(artist)
if (artist && `${artist} ${title}` === query) {
hit._order += 10
} else if (titleNoSymbols && artistNoSymbols && artistNoSymbols + titleNoSymbols === queryNoSymbols) {
hit._order += 9
} else {
if (query.indexOf(title) !== -1) {
hit._order += 4
} else if (titleNoSymbols && queryNoSymbols.indexOf(titleNoSymbols) !== -1) {
hit._order += 3
}
if (primaryArtist && query.indexOf(primaryArtist.name) !== -1) {
hit._order += 4
} else if (artistNoSymbols && queryNoSymbols.indexOf(artistNoSymbols) !== -1) {
hit._order += 3
}
}
}
}
}
if (hits.length > 1) {
hits.sort((a, b) => {
let t = b._order - a._order
if (t) return t
const pv1 = (a.result.stats || 0).pageviews
const pv2 = (b.result.stats || 0).pageviews
t = pv2 - pv1
if (Number.isFinite(t)) return t
if (pv1 > 0) return -1
if (pv2 > 0) return 1
// if order is the same, compare the entry id (greater is more recent)
return (b.result.id - a.result.id) || 0
})
}
// console.log(hits)
return hits
}
function geniusSearch (query, cb, cbError) {
console.log('Genius Search Query', query)
let requestObj = {
url: 'https://genius.com/api/search/song?page=1&q=' + encodeURIComponent(query),
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
t: 'search', // differentiate with other types of requesting
responseType: 'json',
error: function geniusSearchOnError (response) {
console.error(response)
modalAlert(custom.scriptName + '\n\nError in geniusSearch(' + JSON.stringify(query) + ', ' + ('name' in cb ? cb.name : 'cb') + '):' +
'\nRequest status:' + ('status' in response ? response.status : 'unknown') + ' ' + ('statusText' in response ? response.statusText : '') +
('finalUrl' in response ? '\nUrl: ' + response.finalUrl : ''))
invalidateRequestCache(requestObj)
if (typeof cbError === 'function') cbError()
requestObj = null
},
preProcess: function geniusSearchPreProcess (response) {
let jsonData = null
let errorMsg = ''
try {
jsonData = JSON.parse(response.responseText)
} catch (e) {
errorMsg = e
}
if (jsonData !== null) {
const section = (((jsonData || 0).response || 0).sections[0] || 0)
const hits = section.hits || 0
if (typeof hits !== 'object') {
modalAlert(custom.scriptName + '\n\n' + 'Incorrect Response Format' + ' in geniusSearch(' + JSON.stringify(query) + ', ' + ('name' in cb ? cb.name : 'cb') + '):\n\n' + response.responseText)
invalidateRequestCache(requestObj)
if (typeof cbError === 'function') cbError()
requestObj = null
return
}
section.hits = modifyHits(hits, query)
return jsonData
} else {
if (response.responseText.startsWith('<') && !askedToSolveCaptcha) {
askedToSolveCaptcha = true
captchaHint(response.responseText)
}
console.debug(custom.scriptName + '\n\n' + (errorMsg || 'Error') + ' in geniusSearch(' + JSON.stringify(query) + ', ' + ('name' in cb ? cb.name : 'cb') + '):\n\n' + response.responseText) // log into the console window for copying
invalidateRequestCache(requestObj)
if (typeof cbError === 'function') cbError()
requestObj = null
}
},
load: function geniusSearchOnLoad (jsonData, cacheResult) {
if (typeof cacheResult === 'function') cacheResult(jsonData)
cb(jsonData)
}
}
request(requestObj)
}
function loadGeniusSong (song, cb) {
request({
url: song.result.url,
theme: `${genius.option.themeKey}`, // different theme, differnt html cache
error: function loadGeniusSongOnError (response) {
console.error(response)
modalAlert(custom.scriptName + '\n\nError loadGeniusSong(' + JSON.stringify(song) + ', cb):\n' +
'\nRequest status:' + ('status' in response ? response.status : 'unknown') + ' ' + ('statusText' in response ? response.statusText : '') +
('finalUrl' in response ? '\nUrl: ' + response.finalUrl : ''))
},
load: function loadGeniusSongOnLoad (response, cacheResult) {