Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix various exceptions when using a debug Unity build #27

Merged
merged 3 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion BetterSongSearch.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@
<HintPath>$(BeatSaberDir)\Libs\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="protobuf-net">
<HintPath>E:\SteamLibrary\steamapps\common\Beat Saber\Libs\protobuf-net.dll</HintPath>
<HintPath>$(BeatSaberDir)\Libs\protobuf-net.dll</HintPath>
</Reference>
<Reference Include="SegmentedControl">
<HintPath>$(BeatSaberDir)\Beat Saber_Data\Managed\SegmentedControl.dll</HintPath>
Expand Down
76 changes: 37 additions & 39 deletions UI/DownloadHistoryView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,47 +84,45 @@ public async void ProcessDownloads(bool forceTableReload = false) {

RefreshTable(true);

await Task.Run(async () => {
void errored(string message) {
firstEntry.status = DownloadHistoryEntry.DownloadStatus.Failed;
firstEntry.statusDetails = $": {message}";
firstEntry.retries = 69;
}
void errored(string message) {
firstEntry.status = DownloadHistoryEntry.DownloadStatus.Failed;
firstEntry.statusDetails = $": {message}";
firstEntry.retries = 69;
}

try {
var updateRateLimiter = new Stopwatch();
updateRateLimiter.Start();

await SongDownloader.BeatmapDownload(firstEntry, BSSFlowCoordinator.closeCancelSource.Token, (float progress) => {
if(updateRateLimiter.ElapsedMilliseconds < 50)
return;

firstEntry.statusDetails = string.Format("({0:0%}{1})", progress, firstEntry.retries == 0 ? "" : $", retry #{firstEntry.retries} / {RETRY_COUNT}");
firstEntry.downloadProgress = progress;

updateRateLimiter.Restart();

if(firstEntry.UpdateProgressHandler != null)
IPA.Utilities.Async.UnityMainThreadTaskScheduler.Factory.StartNew(firstEntry.UpdateProgressHandler);
});

firstEntry.status = DownloadHistoryEntry.DownloadStatus.Downloaded;
firstEntry.statusDetails = "";
} catch(FileNotFoundException) {
errored("File not Found, Uploader probably deleted it");
} catch(TaskCanceledException) {
errored("Download was cancelled");
} catch(Exception ex) {
if(!(ex is TaskCanceledException)) {
Plugin.Log.Warn("Download failed:");
Plugin.Log.Warn(ex);
}

firstEntry.status = DownloadHistoryEntry.DownloadStatus.Failed;
firstEntry.statusDetails = $"{(firstEntry.retries < 3 ? "(Will retry)" : "")}: Details in log, {ex.Message} ({ex.GetType().Name})";
try {
var updateRateLimiter = new Stopwatch();
updateRateLimiter.Start();

await SongDownloader.BeatmapDownload(firstEntry, BSSFlowCoordinator.closeCancelSource.Token, (float progress) => {
if(updateRateLimiter.ElapsedMilliseconds < 50)
return;

firstEntry.statusDetails = string.Format("({0:0%}{1})", progress, firstEntry.retries == 0 ? "" : $", retry #{firstEntry.retries} / {RETRY_COUNT}");
firstEntry.downloadProgress = progress;

updateRateLimiter.Restart();

if(firstEntry.UpdateProgressHandler != null)
firstEntry.UpdateProgressHandler();
});

firstEntry.status = DownloadHistoryEntry.DownloadStatus.Downloaded;
firstEntry.statusDetails = "";
} catch(FileNotFoundException) {
errored("File not Found, Uploader probably deleted it");
} catch(TaskCanceledException) {
errored("Download was cancelled");
} catch(Exception ex) {
if(!(ex is TaskCanceledException)) {
Plugin.Log.Warn("Download failed:");
Plugin.Log.Warn(ex);
}
firstEntry.downloadProgress = 1f;
});

firstEntry.status = DownloadHistoryEntry.DownloadStatus.Failed;
firstEntry.statusDetails = $"{(firstEntry.retries < 3 ? "(Will retry)" : "")}: Details in log, {ex.Message} ({ex.GetType().Name})";
}
firstEntry.downloadProgress = 1f;

if(firstEntry.status == DownloadHistoryEntry.DownloadStatus.Downloaded) {
// NESTING HELLLL
Expand Down
14 changes: 11 additions & 3 deletions UI/SelectedSongView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ void OnEnable() {

if(selectedSong != null)
SetIsDownloaded(selectedSong.CheckIsDownloaded(), selectedSong.CheckIsDownloadable());

if(soloFreePlayFlowCoordinator == null)
soloFreePlayFlowCoordinator = FindObjectOfType<SoloFreePlayFlowCoordinator>();

if(multiplayerLevelSelectionFlowCoordinator == null)
multiplayerLevelSelectionFlowCoordinator = FindObjectOfType<MultiplayerLevelSelectionFlowCoordinator>();
}

static internal SongPreviewPlayer songPreviewPlayer { get; private set; } = null;
Expand Down Expand Up @@ -116,7 +122,9 @@ internal async void SetSelectedSong(SongSearchSong song, bool selectInTableIfPos
await Task.WhenAll(new[] {
BSSFlowCoordinator.assetLoader.LoadCoverAsync(song.detailsSong, songAssetLoadCanceller.Token).ContinueWith(
x => { coverImage.sprite = x.Result; },
TaskContinuationOptions.OnlyOnRanToCompletion
CancellationToken.None,
TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.FromCurrentSynchronizationContext()
),

!PluginConfig.Instance.loadSongPreviews ? Task.FromResult(1) : BSSFlowCoordinator.assetLoader.LoadPreviewAsync(song.detailsSong, songAssetLoadCanceller.Token).ContinueWith(
Expand Down Expand Up @@ -171,8 +179,8 @@ internal void PlayQueuedSongToPlay() {
songToPlayAfterLoading = null;
}

readonly SoloFreePlayFlowCoordinator soloFreePlayFlowCoordinator = FindObjectOfType<SoloFreePlayFlowCoordinator>();
readonly MultiplayerLevelSelectionFlowCoordinator multiplayerLevelSelectionFlowCoordinator = FindObjectOfType<MultiplayerLevelSelectionFlowCoordinator>();
SoloFreePlayFlowCoordinator soloFreePlayFlowCoordinator;
MultiplayerLevelSelectionFlowCoordinator multiplayerLevelSelectionFlowCoordinator;
static readonly ConstructorInfo LevelSelectionFlowCoordinator_State = AccessTools.FirstConstructor(typeof(LevelSelectionFlowCoordinator.State), x => x.GetParameters().Length == 4);

[UIAction("Play")] void _Play() => PlaySong();
Expand Down
13 changes: 6 additions & 7 deletions UI/Views/SplitViews/UploadDetails.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using HMUI;
using System;
using System.Linq;
using System.Threading.Tasks;
using TMPro;

namespace BetterSongSearch.UI.SplitViews {
Expand All @@ -27,12 +26,12 @@ public async void Populate(SongSearchSong selectedSong) {

songDetailsLoading.gameObject.SetActive(true);

var desc = await Task.Run(async () => {
try {
return await BSSFlowCoordinator.assetLoader.GetSongDescription(selectedSong.detailsSong.key, BSSFlowCoordinator.closeCancelSource.Token);
} catch { }
return "Failed to load description";
});
string desc;
try {
desc = await BSSFlowCoordinator.assetLoader.GetSongDescription(selectedSong.detailsSong.key, BSSFlowCoordinator.closeCancelSource.Token);
} catch {
desc = "Failed to load description";
}

songDetailsLoading.gameObject.SetActive(false);
selectedSongDescription.text = desc;
Expand Down
8 changes: 5 additions & 3 deletions Util/SongDownloader.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using IPA.Utilities.Async;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
Expand Down Expand Up @@ -33,8 +34,9 @@ public static async Task BeatmapDownload(DownloadHistoryEntry entry, Cancellatio
entry.status = DownloadHistoryEntry.DownloadStatus.Extracting;
progressCb(0);

// Not async'ing this as BeatmapDownload() is supposed to be called in a task
ExtractZip(s, folderName, t.Token, progressCb);
var sThread = SynchronizationContext.Current;

await Task.Run(() => ExtractZip(s, folderName, t.Token, (p) => sThread.Post(_ => progressCb(p), null)));
}
}

Expand Down
51 changes: 22 additions & 29 deletions Util/UnityWebrequestWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,42 +21,35 @@ public static async Task<bool> Download(string url, DownloadHandler handler, Can

var req = www.SendWebRequest();

var startThread = SynchronizationContext.Current;

Action<Action> post;

if(startThread == null) {
post = a => a();
} else {
post = a => startThread.Send(_ => a(), null);
}
var lastState = 0f;
var timeouter = new System.Diagnostics.Stopwatch();
timeouter.Start();

while(!req.isDone) {
if(token.IsCancellationRequested) {
www.Abort();
throw new TaskCanceledException();
}

await Task.Run(() => {
var lastState = 0f;
var timeouter = new System.Diagnostics.Stopwatch();
timeouter.Start();
await Task.Delay(20);

while(!req.isDone) {
if(token.IsCancellationRequested) {
post(www.Abort);
throw new TaskCanceledException();
}
if(lastState == www.downloadProgress) {
if(timeouter.ElapsedMilliseconds < (lastState == 0 ? 6000 : 10000))
continue;

if(timeouter.ElapsedMilliseconds > 50000 || (lastState == 0 && timeouter.ElapsedMilliseconds > 6000)) {
post(www.Abort);
throw new TimeoutException();
}
www.Abort();
throw new TimeoutException();
}

Thread.Sleep(20);
lastState = www.downloadProgress;

lastState = www.downloadProgress;
if(progressCb != null && lastState > 0)
progressCb(lastState);

if(progressCb != null && lastState > 0)
post(() => progressCb(lastState));
}
});
timeouter.Restart();
}

return www.isDone && !www.isHttpError && !www.isNetworkError;
return www.isDone && www.result == UnityWebRequest.Result.Success;
} finally {
if(www != null && uwr == null)
www.Dispose();
Expand Down