using System;
using System.Collections;
using System.Collections.Generic;
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
{
/// 요청 1건의 결과. 값은 Str·Num·Bool 로 꺼낸다(경로 예 「account.stamina.amount」 · 「heroes[0].lv」).
public class ServerResult
{
public bool ok;
public long status;
/// 연결 문제(끊김 · 시간 초과 · 서버 오류 5xx) = 다시 보내면 될 수 있다 · false = 서버가 요청을 거절했다.
public bool network;
public string error;
internal JObject json;
/// 서버가 거절한 이유 코드(예 STAGE_LOCKED) · 없으면 "".
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();
}
/// 글자 배열(없으면 빈 목록).
public System.Collections.Generic.List Strings(string path)
{
var list = new System.Collections.Generic.List();
var arr = At(path) as JArray;
if (arr != null)
foreach (var x in arr) list.Add(x.Type == JTokenType.Null ? "" : x.ToString());
return list;
}
/// 배열 길이(없으면 0).
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;
}
}
/// 서버가 게임을 막은 이유 — 서버 점검(시간 · 안내 글) 또는 이용 제한(끝나는 시각). 안내한 뒤 게임을 끝낸다.
public class ServerStop
{
/// SERVER_MAINTENANCE · ACCOUNT_SUSPENDED
public string code;
/// 점검 시작 시각(ISO · 없으면 "").
public string startAt;
/// 점검이 끝나는 시각 · 이용 제한이 끝나는 시각(ISO · 없으면 "" = 이용 제한은 무기한).
public string endAt;
/// 운영자가 적은 점검 안내 글(없으면 "").
public string message;
}
///
/// 서버와 HTTP 로 말하는 가장 아래 층 — 주소 붙이기 · 로그인 증표 · 응답 해석만 한다(게임 규칙은 모른다).
/// 로그인 = 게스트(새 계정) 또는 소셜 계정(구글 플레이 · 게임센터) · 다음부터는 기기에 저장한 재발급 증표로 이어 한다(앱을 켤 때 = 새 세션).
/// 한 계정은 한 기기에서만 접속한다 — 다른 기기에서 접속하면 서버가 이쪽 증표를 못 쓰게 하고(401 SESSION_REPLACED), 그 사실을 LostReason 으로 알린다.
///
public class ServerClient
{
readonly string baseUrl;
readonly int timeoutSec;
/// 재발급 증표를 기기에 저장하는가(테스트 = 저장 안 함 → 매번 새 계정).
readonly bool persist;
string accessToken;
string refreshToken;
// 서버가 「이 세션은 끝났다」고 알리는 이유 코드
public const string LostReplaced = "SESSION_REPLACED"; // 다른 기기에서 접속(또는 로그아웃 · 연동 변경)
public const string LostDeleted = "ACCOUNT_DELETED";
public const string LostExpired = "SESSION_EXPIRED"; // 증표를 다시 받지 못함
public const string LostWithdrawing = "ACCOUNT_WITHDRAWING"; // 탈퇴를 신청한 계정 — 다시 로그인해 탈퇴를 취소해야 한다
// 서버가 「지금은 게임을 할 수 없다」고 알리는 이유 코드 — 다시 보내도 소용없다(안내 뒤 게임 종료)
public const string StopMaintenance = "SERVER_MAINTENANCE"; // 서버 점검 중(점검 중 접속을 허용받은 계정이 아님)
public const string StopSuspended = "ACCOUNT_SUSPENDED"; // 이용이 제한된 계정(블랙리스트)
public const string MethodGuest = "guest";
// 계정 탈퇴 요청의 확인 값 — 유저가 화면에서 안내를 보고 누른 뒤에만 보낸다(서버 규칙과 같은 값)
const string WithdrawConfirm = "WITHDRAW";
// 계정 삭제 요청의 확인 값 — 유저가 화면에서 확인 문구를 입력한 뒤에만 보낸다(서버 규칙과 같은 값)
const string DeleteConfirm = "DELETE";
/// 세션을 잃은 이유(null = 정상) — 값이 있으면 다시 로그인해야 한다.
public string LostReason { get; private set; }
/// 서버가 게임을 막았다(null = 정상) — 서버 점검 · 이용 제한. 값이 있으면 안내한 뒤 게임을 끝낸다.
public ServerStop Stop { get; private set; }
/// 지금 세션의 로그인 방식(guest · google · apple).
public string Method { get; private set; }
/// 테스트 전용 — 정해 둔 응답.
public class FakeResponse
{
public long status;
public string json;
}
///
/// 테스트 전용 — (방식, 주소)를 받아 정해 둔 응답을 돌려주면 서버에 보내지 않고 그 응답을 쓴다(null = 실제로 보낸다).
/// 서버 점검 · 업데이트 필요 · 이용 제한 화면을 서버 전체 설정을 건드리지 않고 확인하려는 것(ServerLink.ClearForce 가 비운다).
///
public static Func Intercept;
// 기기에 저장하지 않는 모드(테스트)의 임시 보관 — 씬을 다시 열어도 남는다(ClearMemory 로 비운다)
static readonly Dictionary memory = new Dictionary();
public static void ClearMemory()
{
memory.Clear();
}
/// storeTag = 저장 칸을 따로 쓰게 하는 꼬리표(테스트에서 「다른 기기」를 흉내 낼 때 — 같은 기기의 로그인 정보를 덮지 않게).
public ServerClient(string baseUrl, int timeoutSec, bool persist, string storeTag = "")
{
this.baseUrl = baseUrl;
this.timeoutSec = timeoutSec;
this.persist = persist;
this.storeTag = storeTag ?? "";
}
readonly string storeTag;
/// 기기에 저장하는 재발급 증표의 키 — 서버 주소마다 따로(개발 서버와 라이브 서버의 계정이 섞이지 않게).
public static string RefreshKey(string baseUrl)
{
return "tks.server.refresh." + Animator.StringToHash(baseUrl).ToString(CultureInfo.InvariantCulture);
}
public bool LoggedIn
{
get { return !string.IsNullOrEmpty(accessToken); }
}
// ---------- 기기에 저장하는 로그인 정보 (서버 주소마다 따로) ----------
string Key(string name)
{
return "tks.server." + name + "." + Animator.StringToHash(baseUrl).ToString(CultureInfo.InvariantCulture) + storeTag;
}
string Load(string name)
{
if (persist) return PlayerPrefs.GetString(Key(name), "");
string v;
return memory.TryGetValue(Key(name), out v) ? v : "";
}
void Keep(string name, string value)
{
if (!persist)
{
memory[Key(name)] = value ?? "";
return;
}
if (string.IsNullOrEmpty(value)) PlayerPrefs.DeleteKey(Key(name));
else PlayerPrefs.SetString(Key(name), value);
PlayerPrefs.Save();
}
/// 이어 할 증표가 기기에 있는가(로그아웃 · 계정 삭제 뒤에는 없다).
public bool HasSaved
{
get { return !string.IsNullOrEmpty(Load("refresh")); }
}
/// 마지막으로 로그인한 방식(guest · google · apple) — 로그아웃해도 남는다(로그인 화면이 「마지막 로그인」을 보여 준다).
public string LastMethod
{
get { return Load("method"); }
}
/// 마지막으로 쓴 시험용 소셜 계정 번호(개발용 입력 칸의 기본값).
public string LastSocialId
{
get { return Load("devid"); }
}
/// 기기의 로그인 상태를 지운다(증표) — 마지막 로그인 방식은 남긴다. all = 방식까지 지운다(계정 삭제).
public void Forget(bool all = false)
{
accessToken = null;
refreshToken = null;
Method = null;
Keep("refresh", "");
if (all)
{
Keep("method", "");
Keep("devid", "");
}
}
/// 날짜처럼 생긴 글자를 날짜로 바꾸지 않고 그대로 읽는다(시각 글자를 ISO 그대로 써야 한다).
static JObject Parse(string text)
{
using (var reader = new JsonTextReader(new StringReader(text)) { DateParseHandling = DateParseHandling.None })
return JObject.Load(reader);
}
/// 요청 1건. auth = 로그인 증표를 붙임 · 401 이면 증표를 한 번 재발급해 다시 보낸다.
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 (Stop != null) yield break; // 서버 점검 · 이용 제한 — 증표를 다시 받아도 소용없다
if (auth && res.status == 403 && res.Message == LostWithdrawing)
{
LostReason = LostWithdrawing;
yield break;
}
if (res.status != 401 || !auth) yield break;
// 서버가 세션이 끝났다고 알렸다(다른 기기에서 접속 · 삭제된 계정) — 증표를 다시 받으려 하지 않는다
if (res.Message == LostReplaced || res.Message == LostDeleted)
{
LostReason = res.Message;
yield break;
}
if (attempt > 0 || string.IsNullOrEmpty(refreshToken))
{
LostReason = LostExpired;
yield break;
}
var again = new ServerResult();
yield return Refresh(again);
if (!again.ok)
{
if (!again.network) LostReason = LostExpired; // 재발급 증표도 받아 주지 않는다 = 다시 로그인해야 한다
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;
var fake = Intercept != null ? Intercept(method, path) : null;
if (fake != null)
{
yield return null; // 실제 요청처럼 한 프레임 뒤에 답한다
res.status = fake.status;
Finish(res, false, fake.json, null);
yield break;
}
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;
Finish(res, transport, req.downloadHandler != null ? req.downloadHandler.text : null, req.error);
}
}
/// 응답을 결과로 정리한다 — 본문 해석 · 성공/연결 문제 구분 · 서버가 게임을 막았는지(점검 · 이용 제한).
void Finish(ServerResult res, bool transport, string text, string transportError)
{
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 ? transportError : "HTTP " + res.status + " " + res.Message;
// 서버 점검 · 이용 제한 = 연결 문제가 아니라 서버가 막은 것 — 다시 보내지 않는다
if (res.status == 503 && res.Message == StopMaintenance)
{
res.network = false;
Stop = new ServerStop { code = StopMaintenance, startAt = res.Str("maintenanceStartAt"), endAt = res.Str("maintenanceEndAt"), message = res.Str("maintenanceMessage") };
}
else if (res.status == 401 && res.Message == StopSuspended)
Stop = new ServerStop { code = StopSuspended, startAt = res.Str("suspendedAt"), endAt = res.Str("suspensionEndAt"), message = "" };
}
/// 테스트용 자동 로그인 — 저장한 증표가 있으면 이어 하기 → 없거나 서버가 받지 않으면 새 게스트 계정(로그인 화면 없음).
public IEnumerator Login(int gameId, ServerResult res)
{
if (HasSaved)
{
yield return Resume(res);
if (res.ok || res.network || Stop != null) yield break; // 연결 문제 · 서버 점검 · 이용 제한이면 새 계정을 만들지 않는다(계정을 잃지 않게)
Debug.LogWarning("[TKS] 저장한 로그인 증표를 서버가 받지 않아 새 게스트 계정으로 시작합니다: " + res.error);
}
yield return GuestLogin(gameId, res);
}
/// 세션 이어 하기(앱을 켤 때) — 저장한 증표로 새 세션을 연다. 같은 계정의 다른 기기 세션은 서버가 끊는다.
public IEnumerator Resume(ServerResult res)
{
refreshToken = Load("refresh");
var body = new JObject { ["refreshToken"] = refreshToken };
yield return SendOnce("POST", "/auth/session", body.ToString(Formatting.None), false, res);
if (res.ok) Store(res, null, null);
}
/// 게스트로 시작 = 새 게스트 계정.
public IEnumerator GuestLogin(int gameId, ServerResult res)
{
var body = new JObject { ["gameId"] = gameId };
yield return SendOnce("POST", "/auth/guest/login", body.ToString(Formatting.None), false, res);
if (res.ok) Store(res, MethodGuest, null);
}
/// 소셜 로그인 — method = google · apple · credential = 기기의 소셜 로그인이 준 증표. 그 소셜 계정에 연동된 게임 계정으로 들어간다(없으면 새 계정).
public IEnumerator SocialLogin(int gameId, string method, string credential, string socialId, ServerResult res)
{
var body = new JObject { ["gameId"] = gameId, ["idToken"] = credential };
yield return SendOnce("POST", "/auth/" + SocialSignIn.PlatformPath(method) + "/login", body.ToString(Formatting.None), false, res);
if (res.ok) Store(res, method, socialId);
}
///
/// 게스트 계정을 소셜 계정에 연동. resolve = null(처음) · keep_current(지금 계정에 연동) · use_existing(기존 연동 계정으로 들어감).
/// 그 소셜 계정이 이미 다른 게임 계정에 연동돼 있으면 409 와 두 계정의 요약(current · existing)이 온다 — 유저가 고른 뒤 resolve 를 붙여 다시 부른다.
///
public IEnumerator Link(string method, string credential, string socialId, string resolve, ServerResult res)
{
var body = new JObject { ["idToken"] = credential };
if (!string.IsNullOrEmpty(resolve)) body["resolve"] = resolve;
yield return SendOnce("POST", "/auth/guest/link/" + SocialSignIn.PlatformPath(method), body.ToString(Formatting.None), true, res);
if (res.ok) Store(res, method, socialId);
}
/// 로그아웃(소셜 계정) — 서버가 증표를 못 쓰게 하고, 기기의 증표를 지운다(마지막 로그인 방식은 남는다).
public IEnumerator Logout(ServerResult res)
{
yield return Send("POST", "/auth/logout", null, true, res);
if (res.ok) Forget();
}
/// 계정 삭제 — 서버가 게임 데이터를 지우고 계정을 삭제 상태로 바꾼다. 기기의 로그인 상태를 전부 지운다.
public IEnumerator DeleteAccount(ServerResult res)
{
var body = new JObject { ["confirm"] = DeleteConfirm };
yield return Send("POST", "/auth/delete-account", body.ToString(Formatting.None), true, res);
if (res.ok) Forget(true);
}
///
/// 계정 탈퇴 신청(소셜 계정) — 서버가 유예 일수 뒤 완전 삭제를 예약하고 로그아웃시킨다. 기기의 증표를 지운다
/// (마지막 로그인 방식은 남는다 — 유예 안에 그 계정으로 다시 로그인하면 탈퇴를 취소할 수 있다).
///
public IEnumerator Withdraw(ServerResult res)
{
var body = new JObject { ["confirm"] = WithdrawConfirm };
yield return Send("POST", "/auth/withdraw", body.ToString(Formatting.None), true, res);
if (res.ok) Forget();
}
/// 계정 탈퇴 취소 — 유예 기간 안에 다시 로그인한 유저가 고른다.
public IEnumerator CancelWithdraw(ServerResult res)
{
yield return Send("POST", "/auth/withdraw/cancel", null, true, 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, null, null);
}
/// 받은 증표를 쓰기 시작하고 기기에 저장한다. method = null 이면 서버가 알려 준 방식(게스트 · 소셜 서비스)을 쓴다.
void Store(ServerResult res, string method, string socialId)
{
accessToken = res.Str("accessToken");
refreshToken = res.Str("refreshToken");
LostReason = null;
Stop = null;
if (method == null && res.Has("accountType")) method = res.Has("provider") ? res.Str("provider") : MethodGuest;
if (method != null) Method = method;
Keep("refresh", refreshToken);
if (method != null) Keep("method", method);
if (!string.IsNullOrEmpty(socialId)) Keep("devid", socialId);
}
}
}