public Promise <Profile> Authenticate(string password) { IsAuthenticating = true; return(new Promise <Profile>((resolve, reject) => { RestClient.Post <Session>(new RequestHelper { Uri = Context.ApiUrl + "/session", EnableDebug = true, BodyString = SecuredOperations.WithCaptcha(new { username = Context.Player.Id, password, }).ToString() }).Then(session => { Context.Player.Settings.PlayerId = session.user.Uid; Context.Player.Settings.LoginToken = session.token; Context.Player.SaveSettings(); return FetchProfile(); } ).Then(profile => { if (profile == null) { reject(new RequestException("Profile not found", true, false, 404, null)); return; } IsAuthenticated = true; OnAuthenticated.Invoke(); resolve(profile); }).CatchRequestError(result => { IsAuthenticated = false; Debug.LogWarning("Sign in failed."); Debug.LogWarning(result); if (result.IsHttpError) { Context.Player.Settings.LoginToken = null; Context.Player.SaveSettings(); } reject(result); }).Finally(() => IsAuthenticating = false); })); }
public void DownloadAndUnpackLevelDialog( Level level, bool allowAbort = true, Action onDownloadSucceeded = default, Action onDownloadAborted = default, Action onDownloadFailed = default, Action <Level> onUnpackSucceeded = default, Action onUnpackFailed = default, bool forceInternational = false ) { if (!Context.OnlinePlayer.IsAuthenticated) { Toast.Next(Toast.Status.Failure, "TOAST_SIGN_IN_REQUIRED".Get()); return; } if (onDownloadSucceeded == default) { onDownloadSucceeded = () => { } } ; if (onDownloadAborted == default) { onDownloadAborted = () => { } } ; if (onDownloadFailed == default) { onDownloadFailed = () => { } } ; if (onUnpackSucceeded == default) { onUnpackSucceeded = _ => { } } ; if (onUnpackFailed == default) { onUnpackFailed = () => { } } ; var dialog = Dialog.Instantiate(); dialog.Message = "DIALOG_DOWNLOADING".Get(); dialog.UseProgress = true; dialog.UsePositiveButton = false; dialog.UseNegativeButton = allowAbort; ulong downloadedSize; var totalSize = 0UL; var downloading = false; var aborted = false; var targetFile = $"{Application.temporaryCachePath}/Downloads/{level.Id}-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.cytoidlevel"; var destFolder = $"{level.Type.GetDataPath()}/{level.Id}"; try { Directory.CreateDirectory(destFolder); } catch (Exception error) { Debug.LogError("Failed to create level folder."); Debug.LogError(error); onDownloadFailed(); return; } if (level.IsLocal) { // Write to the local folder instead destFolder = level.Path; } // Download detail first, then package RequestHelper req; var downloadHandler = new DownloadHandlerFile(targetFile) { removeFileOnAbort = true }; RestClient.Get <OnlineLevel>(req = new RequestHelper { Uri = $"{(forceInternational ? CdnRegion.International.GetApiUrl() : Context.ApiUrl)}/levels/{level.Id}", Headers = Context.OnlinePlayer.GetRequestHeaders(), EnableDebug = true }).Then(it => { if (aborted) { throw new OperationCanceledException(); } totalSize = (ulong)it.Size; downloading = true; var packagePath = (forceInternational ? CdnRegion.International : Context.CdnRegion).GetPackageUrl(level.Id); Debug.Log($"Package path: {packagePath}"); // Get resources return(RestClient.Post <OnlineLevelResources>(req = new RequestHelper { Uri = packagePath, Headers = Context.OnlinePlayer.GetRequestHeaders(), BodyString = SecuredOperations.WithCaptcha(new { }).ToString(), EnableDebug = true })); }).Then(res => { if (aborted) { throw new OperationCanceledException(); } Debug.Log($"Asset path: {res.package}"); // Start download // TODO: Change to HttpClient return(RestClient.Get(req = new RequestHelper { Uri = res.package, DownloadHandler = downloadHandler, WillParseBody = false })); }).Then(async res => { downloading = false; try { onDownloadSucceeded(); } catch (Exception e) { Debug.LogError(e); } dialog.OnNegativeButtonClicked = it => { }; dialog.UseNegativeButton = false; dialog.Progress = 0; dialog.Message = "DIALOG_UNPACKING".Get(); DOTween.To(() => dialog.Progress, value => dialog.Progress = value, 1f, 1f).SetEase(Ease.OutCubic); var success = await Context.LevelManager.UnpackLevelPackage(targetFile, destFolder); if (success) { try { level = (await Context.LevelManager.LoadFromMetadataFiles(level.Type, new List <string> { destFolder + "/level.json" }, true)) .First(); onUnpackSucceeded(level); } catch (Exception e) { Debug.LogError(e); onUnpackFailed(); } } else { try { onUnpackFailed(); } catch (Exception e) { Debug.LogError(e); } } dialog.Close(); File.Delete(targetFile); }).Catch(error => { if (aborted || error is OperationCanceledException || (req != null && req.IsAborted)) { try { onDownloadAborted(); } catch (Exception e) { Debug.LogError(e); } } else { if (!forceInternational && error is RequestException requestException && requestException.StatusCode < 400 && requestException.StatusCode >= 500) { DownloadAndUnpackLevelDialog( level, allowAbort, onDownloadSucceeded, onDownloadAborted, onDownloadFailed, onUnpackSucceeded, onUnpackFailed, true ); } else { Debug.LogError(error); try { onDownloadFailed(); } catch (Exception e) { Debug.LogError(e); } } } dialog.Close(); });