-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
ScoreSaberLeaderboardViewController.cs
499 lines (422 loc) · 21.5 KB
/
ScoreSaberLeaderboardViewController.cs
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
using BeatSaberMarkupLanguage;
using BeatSaberMarkupLanguage.Attributes;
using BeatSaberMarkupLanguage.Parser;
using IPA.Utilities;
using ScoreSaber.Core.Daemons;
using ScoreSaber.Core.Data.Models;
using ScoreSaber.Core.Data.Wrappers;
using ScoreSaber.Core.ReplaySystem;
using ScoreSaber.Core.Services;
using ScoreSaber.Extensions;
using ScoreSaber.UI.Elements.Leaderboard;
using ScoreSaber.UI.Elements.Profile;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using Zenject;
using ScoreSaber.Core.Utils;
using ScoreSaber.Core.ReplaySystem.Data;
using System.Threading;
namespace ScoreSaber.UI.Leaderboard {
internal class ScoreSaberLeaderboardViewController : IInitializable, IDisposable {
#region BSML Components
[UIComponent("root")]
protected readonly RectTransform _root = null;
[UIParams]
private readonly BSMLParserParams _parserParams = null;
[UIComponent("up-button")]
protected readonly Button _upButton = null;
[UIComponent("down-button")]
protected readonly Button _downButton = null;
[UIValue("imageHolders")]
internal List<ProfilePictureView> _ImageHolders = null;
[UIValue("cellClickerHolders")]
internal List<CellClickingView> _cellClickingHolders = null;
[UIValue("entry-holder")]
internal readonly EntryHolder _infoButtons = null;
[UIValue("score-detail-view")]
protected readonly ScoreDetailView _scoreDetailView = null;
[UIComponent("profile-detail-view")]
protected readonly ProfileDetailView _profileDetailView = null;
[UIAction("up-button-click")] private void UpButtonClicked() => DirectionalButtonClicked(false);
[UIAction("down-button-click")] private void DownButtonClicked() => DirectionalButtonClicked(true);
#if PPV3
[UIAction("PPv3-replay-click")] private void PPv3ReplayClick() => _ = PPv3ReplayClicked();
#endif
#endregion
public bool activated { get; private set; }
public int leaderboardPage { get; set; } = 1;
private bool _filterAroundCountry;
private bool _replayDownloading;
private string _currentLeaderboardRefreshId = string.Empty;
private readonly PanelView _panelView;
private readonly DiContainer _container;
private readonly IUploadDaemon _uploadDaemon;
private readonly ReplayLoader _replayLoader;
private readonly PlayerService _playerService;
private readonly LeaderboardService _leaderboardService;
private readonly PlayerDataModel _playerDataModel;
internal readonly PlatformLeaderboardViewController _platformLeaderboardViewController;
// TODO: Put this somewhere nicer?
public enum UploadStatus {
Packaging = 0,
Uploading = 1,
Success = 2,
Retrying = 3,
Error = 4,
Done
}
private bool _isOST = false;
public bool isOST {
get { return _isOST; }
set {
if (!_isOST && value == true) {
ByeImages();
_panelView.SetRankedStatus("N/A (Not Custom Song)");
}
_isOST = value;
}
}
public ScoreSaberLeaderboardViewController(DiContainer container, PanelView panelView, IUploadDaemon uploadDaemon, ReplayLoader replayLoader, PlayerService playerService, LeaderboardService leaderboardService, PlayerDataModel playerDataModel, PlatformLeaderboardViewController platformLeaderboardViewController, StandardLevelDetailViewController standardLevelDetailViewController, List<ProfilePictureView> profilePictureView, List<CellClickingView> cellClickingViews) {
_container = container;
_panelView = panelView;
_uploadDaemon = uploadDaemon;
_replayLoader = replayLoader;
_playerService = playerService;
_playerDataModel = playerDataModel;
_leaderboardService = leaderboardService;
_ImageHolders = profilePictureView;
_cellClickingHolders = cellClickingViews;
_platformLeaderboardViewController = platformLeaderboardViewController;
_infoButtons = new EntryHolder();
_scoreDetailView = new ScoreDetailView();
}
public void Initialize() {
_scoreDetailView.showProfile += scoreDetailView_showProfile;
_scoreDetailView.startReplay += scoreDetailView_startReplay;
_playerService.LoginStatusChanged += playerService_LoginStatusChanged;
_infoButtons.infoButtonClicked += infoButtons_infoButtonClicked;
_uploadDaemon.UploadStatusChanged += uploadDaemon_UploadStatusChanged;
_platformLeaderboardViewController.didActivateEvent += LeaderboardViewActivate;
}
[UIAction("#post-parse")]
public void Parsed() {
_upButton.transform.localScale *= .5f;
_downButton.transform.localScale *= .5f;
_root.name = "ScoreSaberLeaderboardElements";
ByeImages();
activated = true;
}
public void AllowReplayWatching(bool value) {
_scoreDetailView.AllowReplayWatching(value);
}
private void LeaderboardViewActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling) {
if (!firstActivation) { return; }
BSMLParser.instance.Parse(Utilities.GetResourceContent(Assembly.GetExecutingAssembly(), "ScoreSaber.UI.Leaderboard.ScoreSaberLeaderboardViewController.bsml"), _platformLeaderboardViewController.gameObject, this);
_panelView.Show();
_panelView.disabling = delegate () {
if (_scoreDetailView.detailModalRoot != null && _profileDetailView.profileModalRoot != null) {
_scoreDetailView.detailModalRoot.gameObject.SetActive(false);
_profileDetailView.profileModalRoot.gameObject.SetActive(false);
Accessors.animateParentCanvas(ref _scoreDetailView.detailModalRoot) = true;
Accessors.animateParentCanvas(ref _profileDetailView.profileModalRoot) = true;
}
};
_panelView.statusWasSelected = delegate () {
if (_leaderboardService.currentLoadedLeaderboard == null) { return; }
_parserParams.EmitEvent("close-modals");
Application.OpenURL($"https://scoresaber.com/leaderboard/{_leaderboardService.currentLoadedLeaderboard.leaderboardInfoMap.leaderboardInfo.id}");
};
_panelView.rankingWasSelected = delegate () {
_parserParams.EmitEvent("close-modals");
_parserParams.EmitEvent("show-profile");
_profileDetailView.ShowProfile(_playerService.localPlayerInfo.playerId).RunTask();
};
_container.Inject(_profileDetailView);
_playerService.GetLocalPlayerInfo();
}
private void infoButtons_infoButtonClicked(int index) {
if (_leaderboardService.currentLoadedLeaderboard == null) { return; }
_parserParams.EmitEvent("present-score-info");
_scoreDetailView.SetScoreInfo(_leaderboardService.currentLoadedLeaderboard.scores[index], _replayDownloading);
}
private void scoreDetailView_showProfile(string playerId) {
_parserParams.EmitEvent("close-modals");
_parserParams.EmitEvent("show-profile");
_profileDetailView.ShowProfile(playerId).RunTask();
}
private void scoreDetailView_startReplay(ScoreMap score) {
StartReplay(score).RunTask();
}
private void playerService_LoginStatusChanged(PlayerService.LoginStatus loginStatus, string status) {
switch (loginStatus) {
case PlayerService.LoginStatus.Info:
_panelView.SetPromptInfo(status, true);
break;
case PlayerService.LoginStatus.Error:
_panelView.SetPromptError(status, false);
break;
case PlayerService.LoginStatus.Success:
_panelView.SetPromptSuccess(status, false, 3f);
_panelView.RankUpdater().RunTask();
RefreshLeaderboard();
break;
}
Plugin.Log.Debug(status);
}
private void uploadDaemon_UploadStatusChanged(UploadStatus status, string statusText) {
if (statusText != string.Empty) {
Plugin.Log.Debug($"{statusText}");
}
switch (status) {
case UploadStatus.Packaging:
_panelView.Loaded(false);
_panelView.SetPromptInfo(statusText, true);
ByeImages();
break;
case UploadStatus.Uploading:
_panelView.SetPromptInfo(statusText, true);
break;
case UploadStatus.Success:
_panelView.SetPromptSuccess(statusText, false, 2f);
break;
case UploadStatus.Retrying:
_panelView.SetPromptError(statusText, true);
break;
case UploadStatus.Error:
_panelView.SetPromptError(statusText, false, 3f);
break;
case UploadStatus.Done:
RefreshLeaderboard();
_panelView.UpdateRank().RunTask();
break;
}
}
private CancellationTokenSource cancellationToken;
public async Task RefreshLeaderboard(IDifficultyBeatmap difficultyBeatmap, LeaderboardTableView tableView, PlatformLeaderboardsModel.ScoresScope scope, LoadingControl loadingControl, string refreshId) {
try {
_currentLeaderboardRefreshId = refreshId;
if (_uploadDaemon.uploading) { return; }
if (!activated) { return; }
if (scope == PlatformLeaderboardsModel.ScoresScope.AroundPlayer && !_filterAroundCountry) {
_upButton.interactable = false;
_downButton.interactable = false;
} else {
_upButton.interactable = true;
_downButton.interactable = true;
}
ByeImages();
if(cancellationToken != null) {
cancellationToken.Cancel();
cancellationToken.Dispose();
}
cancellationToken = new CancellationTokenSource();
var beatmapData = await difficultyBeatmap.GetBeatmapDataAsync(difficultyBeatmap.level.environmentInfo, _playerDataModel.playerData.playerSpecificSettings);
if (_playerService.loginStatus == PlayerService.LoginStatus.Error) {
SetErrorState(tableView, loadingControl, null, null, "ScoreSaber authentication failed, please restart Beat Saber", false);
ByeImages();
return;
}
if (_playerService.loginStatus != PlayerService.LoginStatus.Success) {
return;
}
await Task.Delay(500); // Delay before doing anything to prevent leaderboard spam
if (_currentLeaderboardRefreshId == refreshId) {
LeaderboardMap leaderboardData = await _leaderboardService.GetLeaderboardData(difficultyBeatmap, scope, leaderboardPage, _playerDataModel.playerData.playerSpecificSettings, _filterAroundCountry);
if (_currentLeaderboardRefreshId != refreshId) {
return; // we need to check this again, since some time may have passed due to waiting for leaderboard data
}
SetRankedStatus(leaderboardData.leaderboardInfoMap.leaderboardInfo);
List<LeaderboardTableView.ScoreData> leaderboardTableScoreData = leaderboardData.ToScoreData();
int playerScoreIndex = GetPlayerScoreIndex(leaderboardData);
if (leaderboardTableScoreData.Count != 0) {
if (scope == PlatformLeaderboardsModel.ScoresScope.AroundPlayer && playerScoreIndex == -1 && !_filterAroundCountry) {
SetErrorState(tableView, loadingControl, null, null, "You haven't set a score on this leaderboard");
} else {
tableView.SetScores(leaderboardTableScoreData, playerScoreIndex);
for (int i = 0; i < leaderboardTableScoreData.Count; i++) {
_ImageHolders[i].setProfileImage(leaderboardData.scores[i].score.leaderboardPlayerInfo.profilePicture, i, cancellationToken.Token);
}
loadingControl.ShowText("", false);
loadingControl.Hide();
if (_uploadDaemon.uploading) {
_panelView.DismissPrompt();
}
}
} else {
if (leaderboardPage > 1) {
SetErrorState(tableView, loadingControl, null, null, "No scores on this page");
} else {
SetErrorState(tableView, loadingControl, null, null, "No scores on this leaderboard, be the first!");
}
ByeImages();
}
}
} catch (HttpErrorException httpError) {
SetErrorState(tableView, loadingControl, httpError);
} catch (Exception exception) {
SetErrorState(tableView, loadingControl, null, exception);
}
}
private void SetRankedStatus(LeaderboardInfo leaderboardInfo) {
if (leaderboardInfo.ranked) {
if (leaderboardInfo.positiveModifiers) {
_panelView.SetRankedStatus("Ranked (DA = +0.02, GN +0.04)");
} else {
_panelView.SetRankedStatus("Ranked (modifiers disabled)");
}
return;
}
if (leaderboardInfo.qualified) {
_panelView.SetRankedStatus("Qualified");
return;
}
if (leaderboardInfo.loved) {
_panelView.SetRankedStatus("Loved");
return;
}
_panelView.SetRankedStatus("Unranked");
}
public int GetPlayerScoreIndex(LeaderboardMap leaderboardMap) {
for (int i = 0; i < leaderboardMap.scores.Length; i++) {
if (leaderboardMap.scores[i].score.leaderboardPlayerInfo.id == _playerService.localPlayerInfo.playerId) {
return i;
}
}
return -1;
}
private void SetErrorState(LeaderboardTableView tableView, LoadingControl loadingControl, HttpErrorException httpErrorException = null, Exception exception = null, string errorText = "Failed to load leaderboard, score won't upload", bool showRefreshButton = true) {
if (httpErrorException != null) {
if (httpErrorException.isNetworkError) {
errorText = "Failed to load leaderboard due to a network error, score won't upload";
_leaderboardService.currentLoadedLeaderboard = null;
}
if (httpErrorException.isScoreSaberError) {
errorText = httpErrorException.scoreSaberError.errorMessage;
if (errorText == "Leaderboard not found") {
_leaderboardService.currentLoadedLeaderboard = null;
_panelView.SetRankedStatus("");
}
}
}
if (exception != null) {
Plugin.Log.Error(exception.ToString());
}
loadingControl.Hide();
loadingControl.ShowText(errorText, showRefreshButton);
tableView.SetScores(new List<LeaderboardTableView.ScoreData>(), -1);
ByeImages();
}
public void DirectionalButtonClicked(bool down) {
if (down) {
leaderboardPage++;
} else {
leaderboardPage--;
}
RefreshLeaderboard();
CheckPage();
}
public void ChangePageButtonsEnabledState(bool state) {
if (state) {
if (leaderboardPage > 1) {
_upButton.interactable = state;
}
_downButton.interactable = state;
} else {
_upButton.interactable = state;
_downButton.interactable = state;
}
}
public void CheckPage() {
if (leaderboardPage > 1) {
_upButton.interactable = true;
} else {
_upButton.interactable = false;
}
}
public void RefreshLeaderboard() {
if (!activated)
return;
_platformLeaderboardViewController?.InvokeMethod<object, PlatformLeaderboardViewController>("Refresh", true, true);
}
public void ChangeScope(bool filterAroundCountry) {
if (activated) {
_filterAroundCountry = filterAroundCountry;
leaderboardPage = 1;
RefreshLeaderboard();
CheckPage();
}
}
internal void ByeImages() {
_ImageHolders.ForEach(holder => holder.ClearSprite());
}
private async Task StartReplay(ScoreMap score) {
_parserParams.EmitEvent("close-modals");
_replayDownloading = true;
try {
_panelView.SetPromptInfo("Downloading Replay...", true);
byte[] replay = await _playerService.GetReplayData(score.parent.difficultyBeatmap, score.parent.leaderboardInfo.id, score);
_panelView.SetPromptInfo("Replay downloaded! Unpacking...", true);
await _replayLoader.Load(replay, score.parent.difficultyBeatmap, score.gameplayModifiers, score.score.leaderboardPlayerInfo.name);
_panelView.SetPromptSuccess("Replay Started!", false, 1f);
} catch (ReplayVersionException ex) {
_panelView.SetPromptError("Unsupported replay version", false);
Plugin.Log.Error($"Failed to start replay (unsupported version): {ex}");
} catch (Exception ex) {
_panelView.SetPromptError("Failed to start replay! Error written to log.", false);
Plugin.Log.Error($"Failed to start replay: {ex}");
}
_replayDownloading = false;
}
public void Dispose() {
_platformLeaderboardViewController.didActivateEvent -= LeaderboardViewActivate;
_playerService.LoginStatusChanged -= playerService_LoginStatusChanged;
_uploadDaemon.UploadStatusChanged -= uploadDaemon_UploadStatusChanged;
_infoButtons.infoButtonClicked -= infoButtons_infoButtonClicked;
_scoreDetailView.startReplay -= scoreDetailView_startReplay;
_scoreDetailView.showProfile -= scoreDetailView_showProfile;
}
#if PPV3
public void UpdatePPv3ButtonState(bool active) {
buttonPPv3Replay.gameObject.SetActive(active);
}
private LeaderboardScoreData _currentPPv3ScoreData = null;
public void CheckPPv3ReplayExists(LeaderboardScoreData scoreData) {
_currentPPv3ScoreData = scoreData;
string levelId = _currentPPv3ScoreData.level.level.levelID.Replace(" WIP", "").Split('_')[2];
string ppv3ReplayPath = $@"{Settings.replayPath}\PPv3-{Shared.ReplaceInvalidChars(_currentPPv3ScoreData.level.level.songName)}-{levelId}-{(_currentPPv3ScoreData.level.difficulty.SerializedName())}.dat";
Plugin.Log.Info(ppv3ReplayPath);
if (File.Exists(ppv3ReplayPath)) {
UpdatePPv3ButtonState(true);
} else {
UpdatePPv3ButtonState(false);
}
}
private async Task PPv3ReplayClicked() {
_replayDownloading = true;
buttonPPv3Replay.interactable = false;
parserParams.EmitEvent("close-modals");
try {
string levelId = _currentPPv3ScoreData.level.level.levelID.Replace(" WIP", "").Split('_')[2];
string ppv3ReplayPath = $@"{Settings.replayPath}\PPv3-{Shared.ReplaceInvalidChars(_currentPPv3ScoreData.level.level.songName)}-{levelId}-{(_currentPPv3ScoreData.level.difficulty.SerializedName())}.dat";
if (File.Exists(ppv3ReplayPath)) {
byte[] replay = File.ReadAllBytes(ppv3ReplayPath);
if (replay != null) {
SetPanelViewPromptInfo("Replay loaded! Unpacking...", true);
await Shared.replayLoader.Load(replay, _currentPPv3ScoreData.level, new GameplayModifiers(), "PPv3");
SetPanelViewPromptSuccess("Replay Started!", false, 1f);
buttonPPv3Replay.interactable = true;
}
}
} catch (Exception ex) {
SetPanelViewPromptError("Failed to start replay! Error written to log.", false);
Plugin.Log.Error($"Failed to start replay: {ex}");
}
_replayDownloading = false;
}
#endif
}
}