ThreeKingdomsSlingshot/Assets/Scripts/OutGame/Net/ServerClient.cs

217 lines
8.6 KiB
C#
Raw Normal View History

using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.Networking;
namespace TKS.OutGame.Net
{
/// <summary>요청 1건의 결과. 값은 Str·Num·Bool 로 꺼낸다(경로 예 「account.stamina.amount」 · 「heroes[0].lv」).</summary>
public class ServerResult
{
public bool ok;
public long status;
/// <summary>연결 문제(끊김 · 시간 초과 · 서버 오류 5xx) = 다시 보내면 될 수 있다 · false = 서버가 요청을 거절했다.</summary>
public bool network;
public string error;
internal JObject json;
/// <summary>서버가 거절한 이유 코드(예 STAGE_LOCKED) · 없으면 "".</summary>
public string Message
{
get { return Str("message"); }
}
internal JToken At(string path)
{
return json != null ? json.SelectToken(path) : null;
}
public bool Has(string path)
{
var t = At(path);
return t != null && t.Type != JTokenType.Null;
}
public string Str(string path)
{
var t = At(path);
return t == null || t.Type == JTokenType.Null ? "" : t.ToString();
}
public long Num(string path)
{
long n;
return long.TryParse(Str(path), NumberStyles.Integer, CultureInfo.InvariantCulture, out n) ? n : 0;
}
public float Float(string path)
{
var t = At(path);
return t == null || (t.Type != JTokenType.Float && t.Type != JTokenType.Integer) ? 0f : (float)t.Value<double>();
}
/// <summary>글자 배열(없으면 빈 목록).</summary>
public System.Collections.Generic.List<string> Strings(string path)
{
var list = new System.Collections.Generic.List<string>();
var arr = At(path) as JArray;
if (arr != null)
foreach (var x in arr) list.Add(x.Type == JTokenType.Null ? "" : x.ToString());
return list;
}
/// <summary>배열 길이(없으면 0).</summary>
public int Count(string path)
{
var arr = At(path) as JArray;
return arr != null ? arr.Count : 0;
}
public bool Bool(string path)
{
var t = At(path);
return t != null && t.Type == JTokenType.Boolean && (bool)t;
}
}
/// <summary>
/// 서버와 HTTP 로 말하는 가장 아래 층 — 주소 붙이기 · 로그인 증표 · 응답 해석만 한다(게임 규칙은 모른다).
/// 로그인 = 기기에 저장한 재발급 증표로 이어 하기 → 없거나 서버가 받지 않으면 새 게스트 계정.
/// </summary>
public class ServerClient
{
readonly string baseUrl;
readonly int timeoutSec;
/// <summary>재발급 증표를 기기에 저장하는가(테스트 = 저장 안 함 → 매번 새 계정).</summary>
readonly bool persist;
string accessToken;
string refreshToken;
public ServerClient(string baseUrl, int timeoutSec, bool persist)
{
this.baseUrl = baseUrl;
this.timeoutSec = timeoutSec;
this.persist = persist;
}
/// <summary>기기에 저장하는 재발급 증표의 키 — 서버 주소마다 따로(개발 서버와 라이브 서버의 계정이 섞이지 않게).</summary>
public static string RefreshKey(string baseUrl)
{
return "tks.server.refresh." + Animator.StringToHash(baseUrl).ToString(CultureInfo.InvariantCulture);
}
public bool LoggedIn
{
get { return !string.IsNullOrEmpty(accessToken); }
}
/// <summary>날짜처럼 생긴 글자를 날짜로 바꾸지 않고 그대로 읽는다(시각 글자를 ISO 그대로 써야 한다).</summary>
static JObject Parse(string text)
{
using (var reader = new JsonTextReader(new StringReader(text)) { DateParseHandling = DateParseHandling.None })
return JObject.Load(reader);
}
/// <summary>요청 1건. auth = 로그인 증표를 붙임 · 401 이면 증표를 한 번 재발급해 다시 보낸다.</summary>
public IEnumerator Send(string method, string path, string body, bool auth, ServerResult res)
{
for (int attempt = 0; attempt < 2; attempt++)
{
yield return SendOnce(method, path, body, auth, res);
if (res.status != 401 || !auth || attempt > 0 || string.IsNullOrEmpty(refreshToken)) yield break;
var again = new ServerResult();
yield return Refresh(again);
if (!again.ok) yield break;
}
}
IEnumerator SendOnce(string method, string path, string body, bool auth, ServerResult res)
{
res.ok = false;
res.network = false;
res.status = 0;
res.error = null;
res.json = null;
using (var req = new UnityWebRequest(baseUrl + path, method))
{
req.downloadHandler = new DownloadHandlerBuffer();
if (body != null)
{
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(body));
req.SetRequestHeader("Content-Type", "application/json");
}
if (auth && !string.IsNullOrEmpty(accessToken)) req.SetRequestHeader("Authorization", "Bearer " + accessToken);
req.timeout = timeoutSec;
UnityWebRequestAsyncOperation op = null;
try
{
op = req.SendWebRequest();
}
catch (Exception e)
{
// 예: 프로젝트 설정이 http 접속을 막고 있을 때(Player Settings > Allow downloads over HTTP)
res.network = true;
res.error = e.Message;
}
if (op == null) yield break;
yield return op;
res.status = req.responseCode;
bool transport = req.result == UnityWebRequest.Result.ConnectionError || req.result == UnityWebRequest.Result.DataProcessingError;
var text = req.downloadHandler != null ? req.downloadHandler.text : null;
if (!string.IsNullOrEmpty(text))
{
try
{
res.json = Parse(text);
}
catch (Exception)
{
res.json = null; // JSON 이 아닌 응답(프록시 오류 화면 등)
}
}
res.ok = !transport && res.status >= 200 && res.status < 300;
res.network = transport || res.status == 0 || res.status >= 500;
if (!res.ok) res.error = transport || res.status == 0 ? req.error : "HTTP " + res.status + " " + res.Message;
}
}
/// <summary>로그인 — 저장한 증표로 이어 하기 → 서버가 받지 않으면 새 게스트 계정.</summary>
public IEnumerator Login(int gameId, ServerResult res)
{
if (persist) refreshToken = PlayerPrefs.GetString(RefreshKey(baseUrl), "");
if (!string.IsNullOrEmpty(refreshToken))
{
yield return Refresh(res);
if (res.ok || res.network) yield break; // 연결 문제면 새 계정을 만들지 않는다(계정을 잃지 않게)
Debug.LogWarning("[TKS] 저장한 로그인 증표를 서버가 받지 않아 새 게스트 계정으로 시작합니다: " + res.error);
}
var body = new JObject { ["gameId"] = gameId };
yield return SendOnce("POST", "/auth/guest/login", body.ToString(Formatting.None), false, res);
if (res.ok) Store(res);
}
IEnumerator Refresh(ServerResult res)
{
var body = new JObject { ["refreshToken"] = refreshToken };
yield return SendOnce("POST", "/auth/refresh", body.ToString(Formatting.None), false, res);
if (res.ok) Store(res);
}
void Store(ServerResult res)
{
accessToken = res.Str("accessToken");
refreshToken = res.Str("refreshToken");
if (!persist) return;
PlayerPrefs.SetString(RefreshKey(baseUrl), refreshToken);
PlayerPrefs.Save();
}
}
}