57 lines
2.2 KiB
C#
57 lines
2.2 KiB
C#
using System;
|
|
using System.Collections;
|
|
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
|
|
public class ProfileInfoFetcher : MonoBehaviour
|
|
{
|
|
/// <summary>GET /players/:playerId/profile. Callback (success, errorOrNull, profileOrNull).</summary>
|
|
public void GetPlayerProfile(int playerId, Action<bool, string, PlayerProfileApiResponse> onComplete)
|
|
{
|
|
StartCoroutine(FetchPlayerProfileCoroutine(playerId, onComplete));
|
|
}
|
|
|
|
IEnumerator FetchPlayerProfileCoroutine(int playerId, Action<bool, string, PlayerProfileApiResponse> onComplete)
|
|
{
|
|
string url = LoginManager.AuthBaseUrl + "/players/" + playerId + "/profile";
|
|
using (var request = UnityWebRequest.Get(url))
|
|
{
|
|
request.downloadHandler = new DownloadHandlerBuffer();
|
|
if (!string.IsNullOrEmpty(LoginManager.AuthToken))
|
|
request.SetRequestHeader("Authorization", "Bearer " + LoginManager.AuthToken);
|
|
|
|
yield return request.SendWebRequest();
|
|
|
|
string text = request.downloadHandler != null ? request.downloadHandler.text : "";
|
|
|
|
if (request.result != UnityWebRequest.Result.Success &&
|
|
request.result != UnityWebRequest.Result.ProtocolError)
|
|
{
|
|
onComplete?.Invoke(false, string.IsNullOrEmpty(request.error) ? "Network error" : request.error, null);
|
|
yield break;
|
|
}
|
|
|
|
if (request.responseCode < 200 || request.responseCode >= 300)
|
|
{
|
|
onComplete?.Invoke(false, string.IsNullOrEmpty(text) ? "Request failed (" + request.responseCode + ")" : text, null);
|
|
yield break;
|
|
}
|
|
|
|
if (string.IsNullOrEmpty(text))
|
|
{
|
|
onComplete?.Invoke(false, "Empty response from server", null);
|
|
yield break;
|
|
}
|
|
|
|
PlayerProfileApiResponse resp = JsonUtility.FromJson<PlayerProfileApiResponse>(text);
|
|
if (resp != null && resp.ok)
|
|
onComplete?.Invoke(true, null, resp);
|
|
else
|
|
{
|
|
string err = resp != null && !string.IsNullOrEmpty(resp.error) ? resp.error : "Request failed";
|
|
onComplete?.Invoke(false, err, null);
|
|
}
|
|
}
|
|
}
|
|
}
|