forked from Splamy/ScoreSaberEnhanced
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscoresaber.user.js
3602 lines (3412 loc) · 122 KB
/
scoresaber.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 ScoreSaberEnhanced
// @version 1.12.0
// @description Adds links to beatsaver, player comparison and various other improvements
// @author Splamy, TheAsuro
// @namespace https://scoresaber.com
// @match http://scoresaber.com/*
// @match https://scoresaber.com/*
// @icon https://scoresaber.com/imports/images/logo.ico
// @updateURL https://github.com/Splamy/ScoreSaberEnhanced/raw/master/scoresaber.user.js
// @downloadURL https://github.com/Splamy/ScoreSaberEnhanced/raw/master/scoresaber.user.js
// @require https://cdn.jsdelivr.net/npm/moment@2.24.0/moment.js
// @run-at document-start
// for Tampermonkey
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @grant GM_info
// for Greasemonkey
// @grant GM.xmlHttpRequest
// @connect unpkg.com
// @connect beatsaver.com
// @connect githubusercontent.com
// @connect bsaber.com
// ==/UserScript==
(function () {
'use strict';
class Global {
}
Global.debug = false;
Global.scoresaber_link = "https://scoresaber.com";
Global.beatsaver_link = "https://beatsaver.com/maps/";
Global.bsaber_songs_link = "https://bsaber.com/songs/";
Global.song_hash_reg = /\/([\da-zA-Z]{40})\.png/;
Global.score_reg = /(score|accuracy):\s*([\d.,]+)%?\s*(\(([\w,]*)\))?/;
Global.leaderboard_reg = /leaderboard\/(\d+)/;
Global.leaderboard_rank_reg = /#([\d,]+)/;
Global.leaderboard_country_reg = /(\?|&)country=(\w+)$/;
Global.user_reg = /u\/(\d+)/;
Global.script_version_reg = /\/\/\s*@version\s+([\d.]+)/;
Global.user_per_page_global_leaderboard = 50;
Global.user_per_page_song_leaderboard = 12;
Global.pp_weighting_factor = 0.965;
function create(tag, attrs, ...children) {
if (tag === undefined)
throw new Error("'tag' not defined");
const ele = document.createElement(tag);
if (attrs) {
for (const [attrName, attrValue] of Object.entries(attrs)) {
if (attrName === "style") {
for (const [styleName, styleValue] of Object.entries(attrs.style)) {
ele.style[styleName] = styleValue;
}
}
else if (attrName === "class") {
if (typeof attrs.class === "string") {
const classes = attrs.class.split(/ /g).filter(c => c.trim().length > 0);
ele.classList.add(...classes);
}
else {
ele.classList.add(...attrs.class);
}
}
else if (attrName === "for") {
ele.htmlFor = attrValue;
}
else if (attrName === "selected") {
ele.selected = (attrValue ? "selected" : undefined);
}
else if (attrName === "disabled") {
if (attrValue)
ele.setAttribute("disabled", undefined);
}
else if (attrName === "data") {
const data_dict = attrs[attrName];
for (const [data_key, data_value] of Object.entries(data_dict)) {
ele.dataset[data_key] = data_value;
}
}
else {
ele[attrName] = attrs[attrName];
}
}
}
into(ele, ...children);
return ele;
}
function clear_children(elem) {
while (elem.lastChild) {
elem.removeChild(elem.lastChild);
}
}
function intor(parent, ...children) {
clear_children(parent);
return into(parent, ...children);
}
function into(parent, ...children) {
for (const child of children) {
if (typeof child === "string") {
if (children.length > 1) {
parent.appendChild(to_node(child));
}
else {
parent.textContent = child;
}
}
else if ("then" in child) {
const dummy = document.createElement("DIV");
parent.appendChild(dummy);
(async () => {
const node = await child;
parent.replaceChild(to_node(node), dummy);
})();
}
else {
parent.appendChild(child);
}
}
return parent;
}
function to_node(elem) {
if (typeof elem === "string") {
const text_div = document.createElement("DIV");
text_div.textContent = elem;
return text_div;
}
return elem;
}
function as_fragment(builder) {
const frag = document.createDocumentFragment();
builder(frag);
return frag;
}
function check(elem) {
if (elem === undefined || elem === null) {
throw new Error("Expected value to not be null");
}
return elem;
}
function get_user_header() {
return check(document.querySelector(".content div.columns h5"));
}
function get_navbar() {
return check(document.querySelector("#navMenu div.navbar-start"));
}
function is_user_page() {
return window.location.href.toLowerCase().startsWith(Global.scoresaber_link + "/u/");
}
function is_song_leaderboard_page() {
return window.location.href.toLowerCase().startsWith(Global.scoresaber_link + "/leaderboard/");
}
function get_current_user() {
if (Global._current_user) {
return Global._current_user;
}
if (!is_user_page()) {
throw new Error("Not on a user page");
}
Global._current_user = get_document_user(document);
return Global._current_user;
}
function get_document_user(doc) {
const username_elem = check(doc.querySelector(".content .title a"));
const user_name = username_elem.innerText.trim();
const user_id = Global.user_reg.exec(window.location.href)[1];
return { id: user_id, name: user_name };
}
function get_home_user() {
if (Global._home_user) {
return Global._home_user;
}
const json = localStorage.getItem("home_user");
if (!json) {
return undefined;
}
Global._home_user = JSON.parse(json);
return Global._home_user;
}
function get_compare_user() {
if (Global.last_selected) {
return Global.last_selected;
}
const stored_last = localStorage.getItem("last_selected");
if (stored_last) {
Global.last_selected = stored_last;
return Global.last_selected;
}
const compare = document.getElementById("user_compare");
if (compare === null || compare === void 0 ? void 0 : compare.value) {
Global.last_selected = compare.value;
return Global.last_selected;
}
return undefined;
}
function insert_compare_feature(elem) {
if (!is_user_page()) {
throw Error("Invalid call to 'insert_compare_feature'");
}
setup_compare_feature_list();
elem.style.marginLeft = "1em";
into(check(Global.feature_list), elem);
}
function insert_compare_display(elem) {
if (!is_user_page()) {
throw Error("Invalid call to 'insert_compare_display'");
}
setup_compare_feature_list();
into(check(Global.feature_display_list), elem);
}
function setup_compare_feature_list() {
if (Global.feature_list === undefined) {
const select_score_order_elem = check(document.querySelector(".content div.select"));
const parent_box_elem = check(select_score_order_elem.parentElement);
Global.feature_list = create("div", { class: "level-item" });
const level_box_elem = create("div", { class: "level" }, Global.feature_list);
parent_box_elem.replaceChild(level_box_elem, select_score_order_elem);
insert_compare_feature(select_score_order_elem);
Global.feature_display_list = create("div", { class: "level-item" });
level_box_elem.insertAdjacentElement("afterend", Global.feature_display_list);
}
}
function set_compare_user(user) {
Global.last_selected = user;
localStorage.setItem("last_selected", user);
}
function set_home_user(user) {
Global._home_user = user;
localStorage.setItem("home_user", JSON.stringify(user));
}
function set_wide_table(value) {
localStorage.setItem("wide_song_table", value ? "true" : "false");
}
function get_wide_table() {
return localStorage.getItem("wide_song_table") === "true";
}
const BMPage = ["song", "songlist", "user"];
const BMButton = ["BS", "OC", "Beast", "BeastBook", "Preview", "BSR"];
const BMPageButtons = BMPage
.map(p => BMButton.map(b => `${p}-${b}`))
.reduce((agg, lis) => [...agg, ...lis], []);
const BMButtonHelp = {
BS: { short: "BS", long: "BeatSaver", tip: "View on BeatSaver" },
OC: { short: "OC", long: "OneClick™", tip: "Download with OneClick™" },
Beast: { short: "BST", long: "BeastSaber", tip: "View/Add rating on BeastSaber" },
BeastBook: { short: "BB", long: "BeastSaber Bookmark", tip: "Bookmark on BeastSaber" },
Preview: { short: "👓", long: "Preview", tip: "Preview map" },
BSR: { short: "❗", long: "BeatSaver Request", tip: "Copy !bsr" },
};
function bmvar(page, button, def) {
return {
display: `var(--sse-show-${page}-${button}, ${def})`,
};
}
function get_button_matrix() {
const json = localStorage.getItem("sse_button_matrix");
if (!json)
return default_button_matrix();
return JSON.parse(json);
}
function default_button_matrix() {
return {
"song-BS": true,
"song-BSR": true,
"song-Beast": true,
"song-BeastBook": true,
"song-OC": true,
"song-Preview": true,
"songlist-BS": true,
"songlist-OC": true,
"user-BS": true,
"user-OC": true,
};
}
function set_button_matrix(bm) {
localStorage.setItem("sse_button_matrix", JSON.stringify(bm));
}
function set_use_new_ss_api(value) {
localStorage.setItem("use_new_api", value ? "true" : "false");
}
function get_use_new_ss_api() {
return (localStorage.getItem("use_new_api") || "true") === "true";
}
function set_bsaber_username(value) {
localStorage.setItem("bsaber_username", value);
}
function get_bsaber_username() {
return (localStorage.getItem("bsaber_username") || undefined);
}
function get_bsaber_bookmarks() {
const data = localStorage.getItem("bsaber_bookmarks");
if (!data)
return [];
return JSON.parse(data);
}
function add_bsaber_bookmark(song_hash) {
const bookmarks = get_bsaber_bookmarks();
bookmarks.push(song_hash);
localStorage.setItem("bsaber_bookmarks", JSON.stringify(bookmarks));
}
function check_bsaber_bookmark(song_hash) {
const bookmarks = get_bsaber_bookmarks();
return bookmarks.includes(song_hash.toLowerCase());
}
function format_en(num, digits) {
if (digits === undefined)
digits = 2;
return num.toLocaleString("en", { minimumFractionDigits: digits, maximumFractionDigits: digits });
}
function toggled_class(bool, css_class) {
return bool ? css_class : "";
}
function number_invariant(num) {
return Number(num.replace(/,/g, ""));
}
function number_to_timespan(num) {
const SECONDS_IN_MINUTE = 60;
const MINUTES_IN_HOUR = 60;
let str = "";
let mod = (num % SECONDS_IN_MINUTE);
str = mod.toFixed(0).padStart(2, "0") + str;
num = (num - mod) / SECONDS_IN_MINUTE;
mod = (num % MINUTES_IN_HOUR);
str = mod.toFixed(0).padStart(2, "0") + ":" + str;
num = (num - mod) / MINUTES_IN_HOUR;
return str;
}
function round2(num) {
return Math.round(num * 100) / 100;
}
function read_inline_date(date) {
return moment.utc(date, "YYYY-MM-DD HH:mm:ss UTC");
}
class Limiter {
constructor() {
this.ratelimit_reset = undefined;
this.ratelimit_remaining = undefined;
}
async wait() {
const now = unix_timestamp();
if (this.ratelimit_reset === undefined || now > this.ratelimit_reset) {
this.ratelimit_reset = undefined;
this.ratelimit_remaining = undefined;
return;
}
if (this.ratelimit_remaining === 0) {
const sleepTime = (this.ratelimit_reset - now);
console.log(`Waiting for cloudflare rate limiter... ${sleepTime}sec`);
await sleep(sleepTime * 1000);
this.ratelimit_remaining = this.ratelimit_limit;
this.ratelimit_reset = undefined;
}
}
setLimitData(remaining, reset, limit) {
this.ratelimit_remaining = remaining;
this.ratelimit_reset = reset;
this.ratelimit_limit = limit;
}
}
async function sleep(timeout) {
return new Promise(resolve => setTimeout(resolve, timeout));
}
function unix_timestamp() {
return Math.round((new Date()).getTime() / 1000);
}
function setup$3() {
Global.debug = localStorage.getItem("debug") === "true";
}
function logc(message, ...optionalParams) {
if (Global.debug) {
console.log("DBG", message, ...optionalParams);
}
}
let SSE_addStyle;
let SSE_xmlhttpRequest;
let SSE_info;
function setup$2() {
if (typeof (GM) !== "undefined") {
logc("Using GM.* extenstions", GM);
SSE_addStyle = GM_addStyle_custom;
SSE_xmlhttpRequest = GM.xmlHttpRequest;
SSE_info = GM.info;
}
else {
logc("Using GM_ extenstions");
SSE_addStyle = GM_addStyle;
SSE_xmlhttpRequest = GM_xmlhttpRequest;
SSE_info = GM_info;
}
}
function GM_addStyle_custom(css) {
const style = create("style");
style.innerHTML = css;
into(document.head, style);
return style;
}
async function load_chart_lib() {
if (typeof Chart !== "function") {
try {
const resp = await fetch("https://scoresaber.com/imports/js/chart.js");
const js = await resp.text();
new Function(js)();
}
catch (err) {
console.warn("Failed to fetch chartjs. Charts might not work", err);
return false;
}
}
return true;
}
function fetch2(url) {
return new Promise((resolve, reject) => {
const host = get_hostname(url);
const request_param = {
method: "GET",
url: url,
headers: { Origin: host },
onload: (req) => {
if (req.status >= 200 && req.status < 300) {
resolve(req.responseText);
}
else {
reject(`request errored: ${url} (${req.status})`);
}
},
onerror: () => {
reject(`request errored: ${url}`);
}
};
SSE_xmlhttpRequest(request_param);
});
}
function get_hostname(url) {
const match = url.match(/:\/\/([^/:]+)/i);
if (match !== null) {
return match[1];
}
else {
return undefined;
}
}
function new_page(link) {
window.open(link, "_blank");
}
class SessionCache {
constructor(prefix) {
this.prefix = prefix;
if (prefix === undefined)
throw Error("Prefix must be set. If you don't want a prefix, explicitely pass ''.");
}
get(key) {
const item = sessionStorage.getItem(this.prefix + key);
if (item === null)
return undefined;
return JSON.parse(item);
}
set(key, value) {
sessionStorage.setItem(this.prefix + key, JSON.stringify(value));
}
}
const api_cache$1 = new SessionCache("saver");
async function get_data_by_hash(song_hash) {
const cached_data = api_cache$1.get(song_hash);
if (cached_data !== undefined)
return cached_data;
try {
const data_str = await fetch2(`https://api.beatsaver.com/maps/hash/${song_hash}`);
const data = JSON.parse(data_str);
api_cache$1.set(song_hash, data);
return data;
}
catch (err) {
logc("Failed to download song data", err);
return undefined;
}
}
async function get_scoresaber_data_by_hash(song_hash, diff_name) {
try {
const diff_value = diff_name === undefined ? 0 : diff_name_to_value(diff_name);
const data_str = await fetch2(`https://beatsaver.com/api/scores/${song_hash}/0?difficulty=${diff_value}&gameMode=0`);
const data = JSON.parse(data_str);
return data;
}
catch (err) {
logc("Failed to download song data", err);
return undefined;
}
}
class Modal {
constructor(elem) {
this.elem = elem;
}
show() {
this.elem.classList.add("is-active");
document.documentElement.classList.add("is-clipped");
}
close(answer) {
this.elem.classList.remove("is-active");
if (!document.querySelector(".modal.is-active"))
document.documentElement.classList.remove("is-clipped");
if (this.after_close)
this.after_close(answer !== null && answer !== void 0 ? answer : "x");
}
dispose() {
document.body.removeChild(this.elem);
}
}
function create_modal(opt) {
var _a, _b, _c, _d;
const base_div = create("div", { class: "modal" });
const modal = new Modal(base_div);
const button_bar = create("div", { class: "buttons" });
let inner;
switch ((_a = opt.type) !== null && _a !== void 0 ? _a : "content") {
case "content":
inner = create("div", { class: "modal-content" }, create("div", { class: "box" }, opt.text, create("br"), button_bar));
break;
case "card":
inner = create("div", { class: "modal-card" }, create("header", { class: "modal-card-head" }, (_b = opt.title) !== null && _b !== void 0 ? _b : ""), create("section", { class: "modal-card-body" }, opt.text), create("footer", { class: "modal-card-foot" }, (_c = opt.footer) !== null && _c !== void 0 ? _c : button_bar));
break;
default:
throw new Error("invalid type");
}
into(base_div, create("div", {
class: "modal-background",
onclick() {
modal.close("x");
}
}), inner, create("button", {
class: "modal-close is-large",
onclick() {
modal.close("x");
}
}));
if (opt.buttons) {
for (const btn_name of Object.keys(opt.buttons)) {
const btn_data = opt.buttons[btn_name];
into(button_bar, create("button", {
class: ["button", (_d = btn_data.class) !== null && _d !== void 0 ? _d : ""],
onclick() {
modal.close(btn_name);
}
}, btn_data.text));
}
}
document.body.appendChild(base_div);
if (opt.default)
modal.show();
return modal;
}
function show_modal(opt) {
return new Promise((resolve) => {
opt.default = true;
const modal = create_modal(opt);
modal.after_close = (answer) => {
modal.dispose();
resolve(answer);
};
});
}
const buttons = {
OkOnly: { x: { text: "Ok", class: "is-primary" } },
};
function get_song_compare_value(song_a, song_b) {
if (song_a.pp > 0 || song_b.pp > 0) {
return [song_a.pp, song_b.pp];
}
else if (song_a.score !== undefined && song_b.score !== undefined) {
return [song_a.score, song_b.score];
}
else if (song_a.accuracy !== undefined && song_b.accuracy !== undefined) {
return [song_a.accuracy * get_song_mod_multiplier(song_a), song_b.accuracy * get_song_mod_multiplier(song_b)];
}
else {
return [-1, -1];
}
}
function get_song_mod_multiplier(song) {
if (!song.mods)
return 1.0;
let multiplier = 1.0;
for (const mod of song.mods) {
switch (mod) {
case "NF":
multiplier -= 0.50;
break;
case "NO":
multiplier -= 0.05;
break;
case "NB":
multiplier -= 0.10;
break;
case "SS":
multiplier -= 0.30;
break;
case "NA":
multiplier -= 0.30;
break;
case "DA":
multiplier += 0.07;
break;
case "GN":
multiplier += 0.11;
break;
case "FS":
multiplier += 0.08;
break;
}
}
return Math.max(0, multiplier);
}
function get_song_hash_from_text(text) {
var _a;
const res = Global.song_hash_reg.exec(text);
return res ? (_a = res[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase() : undefined;
}
async function oneclick_install(song_key) {
const lastCheck = localStorage.getItem("oneclick-prompt");
const prompt = !lastCheck ||
new Date(lastCheck).getTime() + (1000 * 60 * 60 * 24 * 31) < new Date().getTime();
if (prompt) {
localStorage.setItem("oneclick-prompt", new Date().getTime().toString());
const resp = await show_modal({
buttons: {
install: { text: "Get ModAssistant Installer", class: "is-info" },
done: { text: "OK, now leave me alone", class: "is-success" },
},
text: "OneClick™ requires any current ModInstaller tool with the OneClick™ feature enabled.\nMake sure you have one installed before proceeding.",
});
if (resp === "install") {
window.open("https://github.com/Assistant/ModAssistant/releases");
return;
}
}
console.log("Downloading: ", song_key);
window.location.assign(`beatsaver://${song_key}`);
}
function song_equals(a, b) {
if (a === b)
return true;
if (a === undefined || b === undefined)
return false;
return (a.accuracy === b.accuracy &&
a.pp === b.pp &&
a.score === b.score &&
a.time === b.time &&
array_equals(a.mods, b.mods));
}
function array_equals(a, b) {
if (a === b)
return true;
if (a === undefined || b === undefined)
return false;
if (a.length !== b.length)
return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
function parse_mods(mods) {
if (!mods)
return undefined;
const modarr = mods.split(/,/g);
if (modarr.length === 0)
return undefined;
return modarr;
}
function parse_score_bottom(text) {
let score = undefined;
let accuracy = undefined;
let mods = undefined;
const score_res = check(Global.score_reg.exec(text));
if (score_res[1] === "score") {
score = number_invariant(score_res[2]);
}
else if (score_res[1] === "accuracy") {
accuracy = Number(score_res[2]);
}
if (score_res[4]) {
mods = parse_mods(score_res[4]);
}
return { score, accuracy, mods };
}
function get_notes_count(diff_name, characteristic, version) {
var _a;
if (diff_name === "Expert+")
diff_name = "ExpertPlus";
const diff = version.diffs.find((d) => (d.characteristic === characteristic && d.difficulty === diff_name));
return (_a = diff === null || diff === void 0 ? void 0 : diff.notes) !== null && _a !== void 0 ? _a : -1;
}
function calculate_max_score(notes) {
const note_score = 115;
if (notes <= 1)
return note_score * (0 + (notes - 0) * 1);
if (notes <= 5)
return note_score * (1 + (notes - 1) * 2);
if (notes <= 13)
return note_score * (9 + (notes - 5) * 4);
return note_score * (41 + (notes - 13) * 8);
}
function diff_name_to_value(name) {
switch (name) {
case "Easy": return 1;
case "Medium": return 3;
case "Hard": return 5;
case "Expert": return 7;
case "ExpertPlus": return 9;
default: return -1;
}
}
const SCORESABER_LINK = "https://new.scoresaber.com/api";
const API_LIMITER = new Limiter();
async function get_user_recent_songs_dynamic(user_id, page) {
logc(`Fetching user ${user_id} page ${page}`);
if (get_use_new_ss_api()) {
return get_user_recent_songs_new_api_wrap(user_id, page);
}
else {
return get_user_recent_songs_old_api_wrap(user_id, page);
}
}
async function get_user_recent_songs_new_api_wrap(user_id, page) {
const recent_songs = await get_user_recent_songs(user_id, page);
if (!recent_songs) {
return {
meta: { was_last_page: true },
songs: []
};
}
return {
meta: {
was_last_page: recent_songs.scores.length < 8
},
songs: recent_songs.scores.map(s => [String(s.leaderboardId), {
time: s.timeSet,
pp: s.pp,
accuracy: s.maxScore !== 0 ? round2((s.unmodififiedScore / s.maxScore) * 100) : undefined,
score: s.score,
mods: parse_mods(s.mods)
}])
};
}
async function get_user_recent_songs(user_id, page) {
const req = await auto_fetch_retry(`${SCORESABER_LINK}/player/${user_id}/scores/recent/${page}`);
if (req.status === 404) {
return null;
}
const data = await req.json();
return sanitize_song_ids(data);
}
async function get_user_info_basic(user_id) {
const req = await auto_fetch_retry(`${SCORESABER_LINK}/player/${user_id}/basic`);
const data = await req.json();
return sanitize_player_ids(data);
}
async function auto_fetch_retry(url) {
const MAX_RETRIES = 20;
const SLEEP_WAIT = 5000;
for (let retries = MAX_RETRIES; retries >= 0; retries--) {
await API_LIMITER.wait();
const response = await fetch(url);
const remaining = Number(response.headers.get("x-ratelimit-remaining"));
const reset = Number(response.headers.get("x-ratelimit-reset"));
const limit = Number(response.headers.get("x-ratelimit-limit"));
API_LIMITER.setLimitData(remaining, reset, limit);
if (response.status === 429) {
await sleep(SLEEP_WAIT);
}
else {
return response;
}
}
throw new Error("Can't fetch data from new.scoresaber.");
}
function sanitize_player_ids(data) {
data.playerInfo.playerId = String(data.playerInfo.playerId);
return data;
}
function sanitize_song_ids(data) {
for (const s of data.scores) {
s.scoreId = String(s.scoreId);
s.leaderboardId = String(s.leaderboardId);
s.playerId = String(s.playerId);
}
return data;
}
async function get_user_recent_songs_old_api_wrap(user_id, page) {
let doc;
let tries = 5;
while ((!doc || doc.body.textContent === '"Rate Limit Exceeded"') && tries > 0) {
await sleep(500);
doc = await fetch_user_page(user_id, page);
tries--;
}
if (doc === undefined) {
throw Error("Error fetching user page");
}
const last_page_elem = doc.querySelector("nav ul.pagination-list li:last-child a");
const max_pages = Number(last_page_elem.innerText) + 1;
const data = {
meta: {
max_pages,
user_name: get_document_user(doc).name,
was_last_page: page === max_pages,
},
songs: [],
};
const table_row = doc.querySelectorAll("table.ranking.songs tbody tr");
for (const row of table_row) {
const song_data = get_row_data(row);
data.songs.push(song_data);
}
return data;
}
async function fetch_user_page(user_id, page) {
const link = Global.scoresaber_link + `/u/${user_id}&page=${page}&sort=2`;
if (window.location.href.toLowerCase() === link) {
logc("Efficient get :P");
return document;
}
const init_fetch = await (await fetch(link)).text();
const parser = new DOMParser();
return parser.parseFromString(init_fetch, "text/html");
}
function get_row_data(row) {
const rowc = row;
if (rowc.cache) {
return rowc.cache;
}
const leaderboard_elem = check(row.querySelector("th.song a"));
const pp_elem = check(row.querySelector("th.score .ppValue"));
const score_elem = check(row.querySelector("th.score .scoreBottom"));
const time_elem = check(row.querySelector("th.song .time"));
const song_id = Global.leaderboard_reg.exec(leaderboard_elem.href)[1];
const pp = Number(pp_elem.innerText);
const time = read_inline_date(time_elem.title).toISOString();
const { score, accuracy, mods } = parse_score_bottom(score_elem.innerText);
const song = {
pp,
time,
score,
accuracy,
mods,
};
const data = [song_id, song];
rowc.cache = data;
return data;
}
class SseEventHandler {
constructor(eventName) {
this.eventName = eventName;
this.callList = [];
}
invoke(param) {
logc("Event", this.eventName);
for (const func of this.callList) {
func(param);
}
}
register(func) {
this.callList.push(func);
}
}
class SseEvent {
static addNotification(notify) {
this.notificationList.push(notify);
SseEvent.UserNotification.invoke();
}
static getNotifications() {
return this.notificationList;
}
}
SseEvent.UserCacheChanged = new SseEventHandler("UserCacheChanged");
SseEvent.CompareUserChanged = new SseEventHandler("CompareUserChanged");
SseEvent.PinnedUserChanged = new SseEventHandler("PinnedUserChanged");
SseEvent.UserNotification = new SseEventHandler("UserNotification");
SseEvent.StatusInfo = new SseEventHandler("StatusInfo");
SseEvent.notificationList = [];
const CURRENT_DATA_VER = 1;
function load() {
const json = localStorage.getItem("users");
if (!json) {
reset_data();
return;
}
try {
Global.user_list = JSON.parse(json);
}
catch (ex) {
console.error("Failed to read user cache, resetting!");
reset_data();
return;
}
let users_data_ver = get_data_ver();
if (users_data_ver !== CURRENT_DATA_VER) {
logc("Updating usercache format");
if (users_data_ver <= 0) {
for (const user of Object.values(Global.user_list)) {
for (const song of Object.values(user.songs)) {
const time = read_inline_date(song.time);
song.time = time.toISOString();
}
}
users_data_ver = 1;
}
update_data_ver();
save();
logc("Update successful");
}
logc("Loaded usercache", Global.user_list);
}
function reset_data() {
Global.user_list = {};
localStorage.setItem("users", "{}");
update_data_ver();
}
function get_data_ver() {
var _a;
return Number((_a = localStorage.getItem("users_data_ver")) !== null && _a !== void 0 ? _a : "0");
}
function update_data_ver() {
localStorage.setItem("users_data_ver", String(CURRENT_DATA_VER));
}
function save() {
localStorage.setItem("users", JSON.stringify(Global.user_list));
}
function setup_user_compare() {
if (!is_user_page()) {
return;
}
const header = get_user_header();
header.style.display = "flex";
header.style.alignItems = "center";
const user = get_current_user();
into(header, create("div", {
class: "button icon is-medium",
style: { cursor: "pointer" },
data: { tooltip: Global.user_list[user.id] ? "Update score cache" : "Add user to your score cache" },
async onclick() {
await fetch_user(get_current_user().id);
},
}, create("i", { class: ["fas", Global.user_list[user.id] ? "fa-sync" : "fa-bookmark"] })));
const status_elem = create("div");
into(header, status_elem);
SseEvent.StatusInfo.register((status) => intor(status_elem, status.text));
Global.users_elem = create("div");
insert_compare_feature(Global.users_elem);
update_user_compare_dropdown();
SseEvent.UserCacheChanged.register(update_user_compare_dropdown);
SseEvent.UserCacheChanged.register(update_user_compare_songtable);
SseEvent.CompareUserChanged.register(update_user_compare_songtable);
SseEvent.CompareUserChanged.invoke();
}
function update_user_compare_dropdown() {
if (!is_user_page()) {
return;
}
const compare = get_compare_user();
intor(Global.users_elem, create("div", { class: "select" }, create("select", {
id: "user_compare",
onchange() {
const user = this.value;
set_compare_user(user);
SseEvent.CompareUserChanged.invoke();
}
}, create("option", { value: undefined, selected: compare === undefined }, "(None)"), ...Object.entries(Global.user_list).map(([id, user]) => {
return create("option", { value: id, selected: compare === id }, user.name);
}))));
}
function update_user_compare_songtable(other_user) {
var _a;
if (!is_user_page()) {
return;
}
const table = check(document.querySelector("table.ranking.songs"));
const table_row = table.querySelectorAll("tbody tr");
const scoreHeader = check(table.querySelector("tr th.score"));
scoreHeader.textContent = "Score";
table.querySelectorAll(".comparisonScore").forEach(el => el.remove());
table_row.forEach(row => row.style.backgroundImage = "unset");
if (other_user === undefined) {
other_user = get_compare_user();