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

790 lines
40 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace TKS.OutGame.Net
{
/// <summary>
/// 서버와 기기 상태를 맞추는 일꾼(서버 모드에서 세션마다 1개).
/// 1. 접속: 서버 상태 확인 → 기준 정보(재화 목록) → 로그인 → 계정 수신 — 끝날 때까지 화면을 막는다.
/// 2. 전송: 기기에서 이미 반영한 동작을 **순서대로 하나씩** 서버에 보낸다(줄 세우기).
/// 3. 맞춤: 보낼 것이 없어지면 서버의 계정 상태를 다시 받아 기기 값을 덮는다 — 서버가 정본이다.
/// 4. 거절: 서버가 요청을 받아 주지 않으면(기기와 서버가 어긋남) 남은 요청을 버리고 서버 상태로 되돌린다.
/// 5. 끊김: 연결 문제는 몇 번 조용히 다시 보내고, 그래도 안 되면 화면을 막고 「다시 시도」를 받는다.
/// 6. 로그인: 저장한 증표로 이어 하기 → 없으면 로그인 화면(게스트 · 소셜). 다른 기기에서 같은 계정으로 접속하면 이쪽은 안내 뒤 타이틀로 돌아간다.
/// 8. 접속 판정: 앱 버전이 낮으면 「업데이트」 안내와 스토어 바로가기 · 서버 점검 중이면(점검 중 접속을 허용받은 계정이 아닐 때) 점검 시간 안내 →
/// 확인 = 게임 종료 · 이용이 제한된 계정이면 제한 안내(끝나는 시각) → 종료 — 점검 · 이용 제한은 게임 중이어도 다음 요청에서 바로 뜬다.
/// 탈퇴를 신청한 소셜 계정으로 로그인하면 「탈퇴 취소」를 물어본다(PD 2026-11-17).
/// 7. 타이틀 씬: 타이틀 씬이 열리면 세션 없이 먼저 만들어져(ServerLink) 로그인까지 하고, 씬이 바뀌어도 남아 게임 씬의 세션이 이어받는다(Attach) —
/// 로그인 화면은 타이틀 위에 뜨고, 계정 상태는 게임 씬에서 받는다. 게임 씬을 바로 열면(개발 · 테스트) 전 과정을 그 씬에서 한다.
/// </summary>
public class ServerSync : MonoBehaviour
{
public static ServerSync Instance { get; private set; }
public ServerClient Client { get; private set; }
/// <summary>다음으로 넘어가도 되는가 — 타이틀 씬(세션 없음)에서는 로그인이 끝났는가 · 게임 씬에서는 계정 상태까지 받았는가.</summary>
public bool Ready { get; private set; }
/// <summary>타이틀 씬에서 만들어져 게임 씬의 세션을 기다리는 중인가.</summary>
public bool AtTitle
{
get { return session == null; }
}
/// <summary>보내는 중이거나 보낼 것이 남았는가.</summary>
public bool Busy
{
get { return sending || queue.Count > 0; }
}
/// <summary>서버 상태로 맞춘 횟수(접속 때 1회 제외).</summary>
public int Reconciles { get; private set; }
/// <summary>서버가 거절한 횟수.</summary>
public int Rejects { get; private set; }
public string LastError { get; private set; }
/// <summary>화면을 막는 안내가 떠 있는가.</summary>
public bool Blocking
{
get { return overlay != null && overlay.activeSelf; }
}
/// <summary>세션을 잃어(다른 기기에서 접속 등) 타이틀로 돌아가는 안내가 떴는가.</summary>
public bool Kicked { get; private set; }
/// <summary>화면을 막는 안내의 글(테스트 · 확인용).</summary>
public string OverlayMessage
{
get { return overlayText != null && Blocking ? overlayText.text : ""; }
}
/// <summary>안내의 첫 버튼 글(테스트 · 확인용 · 버튼이 없으면 "").</summary>
public string OverlayButtonLabel
{
get { return Blocking && overlayButton != null && overlayButton.activeSelf && overlayButtonLabel != null ? overlayButtonLabel.text : ""; }
}
/// <summary>게임을 계속할 수 없다는 안내(업데이트 필요 · 서버 점검 · 이용 제한)가 떴는가 — 버튼은 스토어 이동 또는 종료뿐이다.</summary>
public bool Halted { get; private set; }
// 접속 판정 안내 글(PD 2026-11-17 지정 문구)
public const string TextUpdate = "새로운 업데이트를 진행하세요";
public const string TextMaintenance = "서버 점검 중입니다.";
public const string TextSuspended = "이용이 제한 된 계정입니다.";
public const string TextWithdrawing = "탈퇴를 신청한 계정입니다.";
// 서버 상태 값 — 점검 중
const string StatusMaintenance = "MAINTENANCE";
class Item
{
public string method;
public string path;
/// <summary>보내는 순간에 만든다(앞 요청의 응답 값 — 예: 전투 세션 — 을 쓸 수 있게).</summary>
public Func<string> body;
public Action<ServerResult> onOk;
public Action<ServerResult> onReject;
/// <summary>응답이 와야 화면을 채울 수 있는 요청(전투 종료 · 등용 · 상자 열기 …) — 오래 걸리면 안내를 띄운다.</summary>
public bool wait;
/// <summary>응답을 받은 직후 서버의 계정 상태로 기기 값을 먼저 맞춘 다음 onOk 를 부른다(결과를 서버가 정하는 동작 — 화면이 맞춰진 값을 읽게).</summary>
public bool syncAfter;
/// <summary>거절이 「기기와 서버가 어긋난 것」이 아닌 요청(쿠폰 코드 틀림 · 우편함 조회 …) — 거절돼도 뒤 요청을 버리지 않고 안내도 띄우지 않는다.</summary>
public bool soft;
}
readonly Queue<Item> queue = new Queue<Item>();
ServerSession session;
// 서버 기준 정보(재화 목록) 응답 — 타이틀 씬에서 받아 두었다가 세션이 생기면 넘긴다
readonly ServerResult goods = new ServerResult();
// 타이틀 씬에서 로그인까지 끝낸 뒤 세션이 이어받았다 = 접속 루틴이 계정 수신부터 한다(한 번만)
bool loggedIn;
bool sending;
bool dirty;
float reconcileAt;
bool retryPressed;
float waitSince = -1f;
// 서버가 주간 랭킹 정산 중이라 입장을 거절했을 때의 이유 코드
const string SettleCode = "RANK_SETTLING";
// 안내 캔버스 = 다른 모든 화면(재화 바 450 · 타이틀 전환 960) 위 · 카메라에 가장 가까운 면
const int OverlayOrder = 990;
const float OverlayPlane = 0.3f;
GameObject overlay;
Text overlayText;
GameObject overlayButton;
Text overlayButtonLabel;
// 둘째 버튼(고르는 안내에서만 — 스토어 두 곳 · 탈퇴 취소/다른 계정)
GameObject overlayButton2;
Text overlayButtonLabel2;
// 버튼이 하는 일(null = 「다시 시도」 · 「확인」 = 기다리는 쪽을 깨운다)
Action overlayAction;
Action overlayAction2;
internal static ServerSync Create(ServerSession session)
{
if (Instance != null && Instance.AtTitle)
{
Instance.Attach(session); // 타이틀 씬에서 로그인한 일꾼을 이어 쓴다
return Instance;
}
Drop(); // 씬을 다시 연 경우 — 앞 세션의 일꾼을 치운다
return Make(session);
}
/// <summary>타이틀 씬에서 — 세션 없이 만들어 로그인까지 한다. 씬이 바뀌어도 남는다.</summary>
internal static ServerSync CreateAtTitle()
{
Drop();
var s = Make(null);
DontDestroyOnLoad(s.gameObject);
return s;
}
static ServerSync Make(ServerSession session)
{
var go = new GameObject("ServerSync");
var s = go.AddComponent<ServerSync>();
s.session = session;
s.Client = new ServerClient(ServerConfig.BaseUrl, ServerConfig.TimeoutSec, !ServerConfig.Forced);
Instance = s;
s.StartCoroutine(s.Run());
return s;
}
/// <summary>지금 일꾼을 치운다(타이틀부터 다시 시작 · 테스트 정리).</summary>
internal static void Drop()
{
if (Instance == null) return;
Destroy(Instance.gameObject);
Instance = null;
}
/// <summary>
/// 게임 씬의 세션이 타이틀 씬에서 만든 일꾼을 이어받는다 — 로그인 증표와 받아 둔 기준 정보를 그대로 쓰고 계정 상태부터 받는다.
/// 타이틀에서 로그인이 끝나기 전에 넘어왔으면(정상 흐름에서는 없음) 접속을 처음부터 다시 한다.
/// </summary>
void Attach(ServerSession s)
{
StopAllCoroutines(); // 타이틀에서 돌던 접속 루틴을 끝내고 세션과 함께 다시 돈다
LoginPanel.Close();
if (overlay != null) Destroy(overlay); // 타이틀 씬 카메라에 그리던 안내 — 이 씬 카메라로 다시 만든다
overlay = null;
session = s;
loggedIn = Ready;
Ready = false;
StartCoroutine(Run());
}
void OnDestroy()
{
if (Instance == this) Instance = null;
}
/// <summary>요청을 줄 맨 뒤에 세운다. onReject = 서버가 거절했거나, 앞 요청이 거절돼 보내지 못하고 버려졌을 때.</summary>
internal void Post(string method, string path, Func<string> body, Action<ServerResult> onOk = null, Action<ServerResult> onReject = null, bool wait = false, bool syncAfter = false, bool soft = false)
{
queue.Enqueue(new Item { method = method, path = path, body = body, onOk = onOk, onReject = onReject, wait = wait, syncAfter = syncAfter, soft = soft });
}
/// <summary>보낼 것이 없어도 서버의 계정 상태를 한 번 다시 받는다(연무장 화면을 열 때 — 날짜 · 시즌이 넘어갔으면 서버가 맞춘 값이 온다).</summary>
internal void Refresh()
{
dirty = true;
reconcileAt = 0f;
}
IEnumerator Run()
{
if (AtTitle) yield return null; // 타이틀 씬의 Start(카메라 준비)가 끝난 뒤에 시작한다
yield return Connect();
if (AtTitle) yield break; // 타이틀 씬 = 로그인까지 — 게임 씬의 세션이 이어받을 때(Attach) 다시 돈다
while (true)
{
if (queue.Count == 0)
{
if (dirty && Time.unscaledTime >= reconcileAt) yield return Reconcile();
yield return null;
continue;
}
yield return SendNext();
}
}
// ---------- 접속 ----------
IEnumerator Connect()
{
var r = new ServerResult();
while (true)
{
ShowOverlay("서버에 접속하는 중…", false);
if (!loggedIn)
{
// 앱 버전을 실어 보낸다 — 서버가 타겟 버전과 견줘 업데이트가 필요한지 알려 준다
yield return Client.Send("GET", "/games/" + ServerConfig.GameId + "/status?ver=" + Uri.EscapeDataString(Application.version ?? ""), null, false, r);
if (!r.ok)
{
yield return AskRetry("서버에 접속할 수 없습니다", r);
continue;
}
if (r.Bool("updateRequired")) yield return UpdateRequired(r); // 돌아오지 않는다 — 스토어에서 업데이트해야 한다
// 서버 점검 중이어도 여기서 막지 않는다 — 점검 중 접속을 허용받은 계정(화이트리스트)인지는 로그인해야 알 수 있다.
// 허용받지 않은 계정은 로그인 · 요청을 서버가 거절하고(Client.Stop), 그때 점검 안내를 띄운다
bool maintenance = r.Str("status") == StatusMaintenance;
yield return Client.Send("GET", "/tks/config", null, false, goods);
if (!goods.ok)
{
yield return AskRetry("서버 기준 정보를 받지 못했습니다", goods);
continue;
}
yield return Authenticate(r, maintenance ? TextMaintenance + "\n점검 중 접속이 허용된 계정만 로그인할 수 있습니다." : null);
if (Client.Stop != null) yield return Stopped(); // 서버 점검 · 이용 제한 — 돌아오지 않는다
if (!r.ok)
{
yield return AskRetry("로그인하지 못했습니다", r);
continue;
}
if (r.Has("withdrawal"))
{
// 탈퇴를 신청한 계정 — 취소하고 계속할지 물어본다(다른 계정으로 로그인 = 로그아웃 뒤 처음부터)
bool keep = false;
yield return AskWithdrawal(r.Str("withdrawal.deleteAt"), v => keep = v);
if (!keep) continue;
ShowOverlay("서버에 접속하는 중…", false);
}
}
loggedIn = false; // 아래에서 막혀 다시 시도할 때는 처음부터 한다
if (AtTitle)
{
// 타이틀 씬 — 로그인까지 끝났다. 타이틀이 「Press Any Key」를 띄우고, 계정 상태는 게임 씬의 세션이 이어받아 받는다
Ready = true;
HideOverlay();
yield break;
}
if (!session.LoadGoodsTable(goods))
{
yield return AskRetry("서버 기준 정보를 받지 못했습니다", goods);
continue;
}
ShowOverlay("서버에 접속하는 중…", false);
// 기기 시간대를 실어 보낸다 — 새 계정이면 서버가 이때 계정에 고정한다(일일 초기화 = 그 나라 0시)
yield return Client.Send("GET", ServerSession.AccountPath(), null, true, r);
if (Client.Stop != null) yield return Stopped();
if (!r.ok)
{
yield return AskRetry("계정 정보를 받지 못했습니다", r);
continue;
}
session.ApplySnapshot(r, true);
Ready = true;
HideOverlay();
yield break;
}
}
// ---------- 로그인 ----------
/// <summary>
/// 로그인 — 기기에 저장한 증표가 있으면 그 계정으로 이어 하고(마지막에 로그인한 계정), 없거나 서버가 받지 않으면 로그인 화면을 띄운다.
/// 로그인 화면 = 게스트로 시작 · 소셜 계정(구글 플레이 · 게임센터)으로 로그인. 끝나면 r.ok (연결 문제면 r.network).
/// </summary>
IEnumerator Authenticate(ServerResult r, string firstNotice = null)
{
if (ServerLink.AutoLogin)
{
yield return Client.Login(ServerConfig.GameId, r); // 테스트: 화면 없이 이어 하기 → 없으면 새 게스트
yield break;
}
string notice = firstNotice;
if (Client.HasSaved)
{
yield return Client.Resume(r);
if (r.ok || r.network || Client.Stop != null) yield break; // 서버 점검 · 이용 제한이면 저장한 로그인을 지우지 않는다
notice = "로그인 정보가 만료되었거나 다른 기기에서 접속했습니다.\n다시 로그인해 주세요.";
Client.Forget();
}
while (true)
{
HideOverlay();
string method = null, socialId = null;
var cam = OutGameRoot.Instance != null && OutGameRoot.Instance.Cam != null ? OutGameRoot.Instance.Cam : Camera.main;
EnsureInput();
LoginPanel.Show(transform, cam, Client.LastMethod, Client.LastSocialId, notice, (m, id) =>
{
method = m;
socialId = id;
});
while (method == null) yield return null;
LoginPanel.Close();
ShowOverlay("로그인하는 중…", false);
if (method == ServerClient.MethodGuest) yield return Client.GuestLogin(ServerConfig.GameId, r);
else
{
string credential = null, error = null;
bool done = false;
SocialSignIn.SignIn(method, socialId, (c, e) =>
{
credential = c;
error = e;
done = true;
});
while (!done) yield return null;
if (credential == null)
{
notice = error;
continue;
}
yield return Client.SocialLogin(ServerConfig.GameId, method, credential, socialId, r);
}
if (r.ok || r.network || Client.Stop != null) yield break;
notice = "로그인하지 못했습니다 (" + (string.IsNullOrEmpty(r.Message) ? r.error : r.Message) + ")";
}
}
/// <summary>
/// 세션을 잃었다(다른 기기에서 이 계정으로 접속 · 삭제된 계정 · 증표 만료) — 줄 선 요청을 버리고 안내한 뒤 타이틀(로그인 화면)로 돌아간다.
/// 한 계정은 한 기기에서만 접속한다(PD 2026-11-17).
/// </summary>
IEnumerator Kick()
{
var dropped = queue.ToArray();
queue.Clear();
sending = false;
waitSince = -1f;
Ready = false;
Kicked = true;
string reason = Client.LostReason;
LastError = "세션 종료: " + reason;
Debug.LogWarning("[TKS] " + LastError);
var lost = new ServerResult { ok = false, status = 401, error = LastError };
foreach (var d in dropped)
if (d.onReject != null) d.onReject(lost);
Client.Forget();
string msg = reason == ServerClient.LostReplaced ? "다른 기기에서 이 계정으로 접속하여\n연결이 종료되었습니다."
: reason == ServerClient.LostDeleted ? "삭제된 계정입니다."
: reason == ServerClient.LostWithdrawing ? TextWithdrawing + "\n다시 로그인하면 탈퇴를 취소할 수 있습니다."
: "로그인 정보가 만료되었습니다.";
retryPressed = false;
ShowOverlay(msg + "\n<size=26>확인을 누르면 타이틀 화면으로 돌아갑니다</size>", true, "확인");
while (!retryPressed) yield return null;
ServerLink.Restart();
while (true) yield return null; // 씬이 바뀔 때까지
}
// ---------- 계정 (옵션 화면이 부른다) ----------
/// <summary>지금 로그인한 계정의 로그인 정보(게스트인가 · 어느 소셜 계정인가).</summary>
public void AccountInfo(Action<ServerResult> done)
{
Post("GET", "/auth/session", null, done, done, false, false, true);
}
/// <summary>로그아웃(소셜 계정) → 타이틀의 로그인 화면으로. 실패하면 fail(이유).</summary>
public void Logout(Action<string> fail)
{
StartCoroutine(Leave(Client.Logout, "로그아웃하는 중…", fail));
}
/// <summary>
/// 계정 탈퇴 신청(소셜 계정) → 서버가 유예 일수 뒤 완전 삭제를 예약하고 로그아웃시킨다 → 타이틀의 로그인 화면으로.
/// 유예 안에 같은 소셜 계정으로 다시 로그인하면 탈퇴를 취소할 수 있다.
/// </summary>
public void Withdraw(Action<string> fail)
{
StartCoroutine(Leave(Client.Withdraw, "계정 탈퇴를 신청하는 중…", fail));
}
/// <summary>계정 삭제(게스트) → 서버가 데이터를 지우고, 기기의 로그인 상태를 초기화한 뒤 타이틀의 로그인 화면으로.</summary>
public void DeleteAccount(Action<string> fail)
{
StartCoroutine(Leave(Client.DeleteAccount, "계정을 삭제하는 중…", fail));
}
IEnumerator Leave(Func<ServerResult, IEnumerator> request, string busy, Action<string> fail)
{
while (Busy) yield return null; // 줄 선 요청을 먼저 다 보낸다
ShowOverlay(busy, false);
var r = new ServerResult();
yield return request(r);
if (Client.Stop != null) yield return Stopped();
HideOverlay();
if (!r.ok)
{
if (fail != null) fail(r.network ? "서버와 연결되지 않았습니다" : r.Message);
yield break;
}
Ready = false;
ServerLink.Restart();
}
/// <summary>
/// 게스트 계정을 소셜 계정에 연동. done(r): r.ok = 끝(연동됨 · 또는 기존 계정으로 들어감 → 타이틀로 다시 시작) ·
/// r.status 409 = 그 소셜 계정이 이미 다른 게임 계정에 연동돼 있다(r 에 current · existing 요약) → 유저가 고른 뒤 resolve 를 붙여 다시 부른다 · 그 밖 = 실패.
/// </summary>
public void Link(string method, string socialId, string resolve, Action<ServerResult> done)
{
StartCoroutine(LinkRoutine(method, socialId, resolve, done));
}
IEnumerator LinkRoutine(string method, string socialId, string resolve, Action<ServerResult> done)
{
while (Busy) yield return null;
var r = new ServerResult();
string credential = null, error = null;
bool signed = false;
SocialSignIn.SignIn(method, socialId, (c, e) =>
{
credential = c;
error = e;
signed = true;
});
while (!signed) yield return null;
if (credential == null)
{
r.error = error;
done(r);
yield break;
}
ShowOverlay("계정을 연동하는 중…", false);
yield return Client.Link(method, credential, socialId, resolve, r);
HideOverlay();
if (r.ok && r.Str("result") == LinkSwitched)
{
// 기존 연동 계정으로 들어갔다 — 그 계정의 데이터로 다시 시작한다
done(r);
Ready = false;
ServerLink.Restart();
yield break;
}
if (r.ok) Refresh();
done(r);
}
// 연동 응답의 result 값 — 기존 연동 계정으로 들어갔을 때
const string LinkSwitched = "switched";
// ---------- 전송 ----------
IEnumerator SendNext()
{
var it = queue.Peek();
sending = true;
var r = new ServerResult();
int tries = 0;
if (it.wait) waitSince = Time.unscaledTime;
while (true)
{
yield return Client.Send(it.method, it.path, it.body != null ? it.body() : null, true, r);
if (r.ok || !r.network) break;
if (tries < ServerConfig.Retry)
{
tries++;
yield return new WaitForSecondsRealtime(0.5f * tries);
continue;
}
yield return AskRetry("서버와 연결이 끊겼습니다", r); // 「다시 시도」 = 같은 요청을 다시 보낸다
tries = 0;
}
waitSince = -1f;
HideOverlay();
if (Client.Stop != null) yield return Stopped(); // 게임 중에 서버 점검이 시작됐다 · 이용이 제한됐다 — 안내 뒤 게임 종료(돌아오지 않는다)
if (Client.LostReason != null)
{
yield return Kick(); // 다른 기기에서 접속했다 등 — 타이틀로 돌아간다
yield break;
}
queue.Dequeue();
sending = false;
if (r.ok)
{
if (it.syncAfter)
{
sending = true; // 맞추는 동안도 「보내는 중」
if (it.wait) waitSince = Time.unscaledTime;
yield return Reconcile(true);
waitSince = -1f;
HideOverlay();
sending = false;
}
if (it.onOk != null) it.onOk(r);
dirty = true;
reconcileAt = Time.unscaledTime + ServerConfig.ReconcileDelay;
yield break;
}
if (it.soft)
{
// 어긋난 것이 아닌 거절(쿠폰 코드 틀림 등) — 그 요청만 실패로 알리고 줄은 그대로 둔다
if (it.onReject != null) it.onReject(r);
yield break;
}
// 서버가 거절 = 기기와 서버가 어긋났다 → 뒤에 줄 선 요청은 어긋난 상태에서 만든 것이라 버리고 서버 상태로 되돌린다
Rejects++;
LastError = it.method + " " + it.path + " → " + r.error;
Debug.LogWarning("[TKS] 서버가 요청을 거절했습니다: " + LastError);
var dropped = queue.ToArray();
queue.Clear();
if (it.onReject != null) it.onReject(r);
foreach (var d in dropped)
if (d.onReject != null) d.onReject(r);
dirty = true;
reconcileAt = 0f;
yield return Reconcile();
Notice(r.Message == SettleCode ? ArenaRules.SettleNotice : "서버 기록과 달라 다시 불러왔습니다 (" + r.Message + ")");
}
/// <summary>서버의 계정 상태로 기기 값을 덮는다. 받는 사이에 새 요청이 줄 섰으면 버리고 다음에 다시 한다(force = 줄이 있어도 덮는다).</summary>
IEnumerator Reconcile(bool force = false)
{
var r = new ServerResult();
yield return Client.Send("GET", "/tks/account", null, true, r);
if (Client.Stop != null) yield return Stopped();
if (Client.LostReason != null)
{
yield return Kick();
yield break;
}
if (!r.ok)
{
reconcileAt = Time.unscaledTime + Mathf.Max(1f, ServerConfig.ReconcileDelay) * 3f; // 조금 뒤에 다시
yield break;
}
if (queue.Count > 0 && !force) yield break;
session.ApplySnapshot(r, false);
dirty = false;
Reconciles++;
}
void Update()
{
// 응답을 기다려야 하는 요청이 오래 걸리면 안내
if (waitSince >= 0f && !Blocking && Time.unscaledTime - waitSince >= ServerConfig.WaitNotice) ShowOverlay("서버에 기록하는 중…", false);
}
// ---------- 안내 ----------
static void Notice(string msg)
{
if (OutGameRoot.Instance != null) OutGameRoot.Instance.Toast(msg);
}
IEnumerator AskRetry(string msg, ServerResult r)
{
LastError = msg + (r != null && !string.IsNullOrEmpty(r.error) ? " — " + r.error : "");
Debug.LogWarning("[TKS] " + LastError);
retryPressed = false;
ShowOverlay(msg + (r != null && !string.IsNullOrEmpty(r.error) ? "\n<size=26>" + r.error + "</size>" : ""), true);
while (!retryPressed) yield return null;
}
/// <summary>안내의 첫 버튼 누름(화면 버튼 · 테스트) — 「다시 시도」 · 「확인」 · 「종료」 · 스토어 이동 · 「탈퇴 취소」.</summary>
public void PressRetry()
{
if (overlayAction != null) overlayAction();
else retryPressed = true;
}
/// <summary>안내의 둘째 버튼 누름(화면 버튼 · 테스트) — 고르는 안내에서만 있다.</summary>
public void PressSecond()
{
if (overlayAction2 != null) overlayAction2();
}
// ---------- 접속 판정 안내 (업데이트 필요 · 서버 점검 · 이용 제한 · 탈퇴 신청 계정) ----------
/// <summary>서버 시각 글자(ISO · UTC) → 이 기기의 시각 「yyyy-MM-dd HH:mm」. 비었거나 읽지 못하면 "".</summary>
public static string LocalTime(string iso)
{
DateTime t;
if (string.IsNullOrEmpty(iso) || !DateTime.TryParse(iso, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out t)) return "";
return t.ToLocalTime().ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
}
/// <summary>줄 선 요청을 버리고(알림) 더 진행하지 않는 상태로 둔다 — 게임을 계속할 수 없는 안내를 띄우기 전에.</summary>
void Halt(string why)
{
var dropped = queue.ToArray();
queue.Clear();
sending = false;
waitSince = -1f;
Ready = false;
Halted = true;
LastError = why;
Debug.LogWarning("[TKS] " + why);
LoginPanel.Close();
var lost = new ServerResult { ok = false, status = 0, error = why };
foreach (var d in dropped)
if (d.onReject != null) d.onReject(lost);
}
/// <summary>
/// 업데이트 필요 — 앱 버전이 서버의 타겟 버전보다 낮다. 「새로운 업데이트를 진행하세요」 + 스토어 바로가기(안드로이드 = 구글 플레이 스토어 · iOS = 애플 앱스토어).
/// 에디터 등 그 밖의 플랫폼에서는 두 스토어 버튼을 모두 보여 준다(확인용). 더 진행하지 않는다.
/// </summary>
IEnumerator UpdateRequired(ServerResult r)
{
Halt("업데이트 필요: 앱 버전 " + Application.version + " < 타겟 버전 " + r.Str("version"));
string android = r.Str("storeUrls.android"), ios = r.Str("storeUrls.ios");
string msg = TextUpdate + "\n<size=26>스토어에서 최신 버전으로 업데이트한 뒤 다시 실행해 주세요</size>";
if (Application.platform == RuntimePlatform.Android) ShowChoice(msg, "Play 스토어로 이동", () => ServerLink.OpenStore(android), null, null);
else if (Application.platform == RuntimePlatform.IPhonePlayer) ShowChoice(msg, "App Store로 이동", () => ServerLink.OpenStore(ios), null, null);
else ShowChoice(msg, "Play 스토어", () => ServerLink.OpenStore(android), "App Store", () => ServerLink.OpenStore(ios));
while (true) yield return null;
}
/// <summary>
/// 서버가 게임을 막았다 — 서버 점검(「서버 점검 중입니다.」 + 점검 시간 → 확인 = 게임 종료) 또는
/// 이용 제한(「이용이 제한 된 계정입니다.」 + 제한이 끝나는 시각(정해졌을 때만) → 종료 버튼만). 접속할 때도, 게임 중에도 뜬다. 돌아오지 않는다.
/// </summary>
IEnumerator Stopped()
{
var stop = Client.Stop;
bool maintenance = stop.code == ServerClient.StopMaintenance;
Halt((maintenance ? "서버 점검" : "이용 제한") + ": " + stop.code);
string msg;
if (maintenance)
{
string from = LocalTime(stop.startAt), to = LocalTime(stop.endAt);
msg = TextMaintenance
+ (from.Length > 0 || to.Length > 0 ? "\n<size=28>점검 시간 " + from + " ~ " + to + "</size>" : "")
+ (string.IsNullOrEmpty(stop.message) ? "" : "\n<size=26>" + stop.message + "</size>")
+ "\n<size=24>확인을 누르면 게임이 종료됩니다</size>";
}
else
{
string until = LocalTime(stop.endAt);
msg = TextSuspended + (until.Length > 0 ? "\n<size=28>제한 해제 " + until + "</size>" : "");
}
ShowChoice(msg, maintenance ? "확인" : "종료", ServerLink.Quit, null, null);
while (true) yield return null;
}
/// <summary>
/// 탈퇴를 신청한 계정으로 로그인했다 — 삭제 예정 시각을 알리고 고르게 한다: 「탈퇴 취소」(계속 플레이) · 「다른 계정으로 로그인」(로그아웃).
/// done(true) = 취소하고 계속 · done(false) = 로그아웃했다(로그인 화면으로).
/// </summary>
IEnumerator AskWithdrawal(string deleteAt, Action<bool> done)
{
var res = new ServerResult();
string note = "";
while (true)
{
int pick = 0;
ShowChoice(TextWithdrawing + "\n<size=28>" + LocalTime(deleteAt) + " 에 계정과 모든 데이터가 완전히 삭제됩니다.\n탈퇴를 취소하고 계속 플레이하시겠습니까?</size>" + note,
"탈퇴 취소", () => pick = 1, "다른 계정으로 로그인", () => pick = 2);
while (pick == 0) yield return null;
if (pick == 1)
{
ShowOverlay("탈퇴를 취소하는 중…", false);
yield return Client.CancelWithdraw(res);
if (Client.Stop != null) yield return Stopped();
if (res.ok)
{
done(true);
yield break;
}
note = "\n<size=24><color=#ff9090>탈퇴를 취소하지 못했습니다 (" + (res.network ? "서버와 연결되지 않았습니다" : res.Message) + ")</color></size>";
continue;
}
ShowOverlay("로그아웃하는 중…", false);
yield return Client.Logout(res);
Client.Forget(); // 서버에 닿지 않았어도 기기의 증표는 지운다 — 로그인 화면으로 돌아간다
done(false);
yield break;
}
}
/// <summary>
/// 버튼 누름을 받는 장치가 씬에 없으면 만든다 — 타이틀 씬은 키 · 터치만 읽어서 장치가 없다(게임 씬은 전투 HUD 가 만든다).
/// 지금 씬에 만들어 씬과 함께 사라지게 한다(이 일꾼은 씬을 넘어가므로 자식으로 두지 않는다).
/// </summary>
static void EnsureInput()
{
if (EventSystem.current != null || FindFirstObjectByType<EventSystem>() != null) return;
var es = new GameObject("EventSystem");
es.AddComponent<EventSystem>();
es.AddComponent<StandaloneInputModule>();
}
void ShowOverlay(string msg, bool button, string buttonLabel = "다시 시도")
{
ShowChoice(msg, button ? buttonLabel : null, null, null, null);
}
/// <summary>
/// 안내를 띄운다 — 버튼 0~2개. label1 = null 이면 버튼 없음 · action1 = null 이면 첫 버튼이 기다리는 쪽을 깨운다(「다시 시도」 · 「확인」).
/// 버튼이 하나면 가운데, 둘이면 나란히 놓는다.
/// </summary>
void ShowChoice(string msg, string label1, Action action1, string label2, Action action2)
{
if (label1 != null) EnsureInput();
if (overlay == null) BuildOverlay();
overlayText.text = msg;
overlayAction = action1;
overlayAction2 = action2;
bool two = label1 != null && label2 != null;
overlayButton.SetActive(label1 != null);
overlayButton2.SetActive(two);
if (label1 != null) overlayButtonLabel.text = label1;
if (two) overlayButtonLabel2.text = label2;
((RectTransform)overlayButton.transform).anchoredPosition = new Vector2(two ? -ButtonGapX : 0f, ButtonY);
((RectTransform)overlayButton2.transform).anchoredPosition = new Vector2(ButtonGapX, ButtonY);
overlay.SetActive(true);
}
// 안내 버튼 자리 · 크기
const float ButtonY = -190f;
const float ButtonGapX = 215f;
static readonly Vector2 ButtonSize = new Vector2(400f, 110f);
void HideOverlay()
{
if (overlay != null) overlay.SetActive(false);
}
/// <summary>화면 전체를 덮어 누름을 막는 안내(가끔만 뜨고 평소엔 꺼 둔다 · 자기 캔버스 1개 = 사건 때만 바뀌는 층).</summary>
void BuildOverlay()
{
overlay = new GameObject("ServerOverlay");
overlay.transform.SetParent(transform, false);
var cam = OutGameRoot.Instance != null && OutGameRoot.Instance.Cam != null ? OutGameRoot.Instance.Cam : Camera.main;
UiLayer.Root(overlay, cam, OverlayOrder, OverlayPlane, OutGameRoot.Reference, UiRate.Event);
var dim = UiKit.Fill("Dim", overlay.transform);
var img = dim.gameObject.AddComponent<Image>();
img.color = new Color(0f, 0f, 0f, 0.72f);
img.raycastTarget = true; // 아래 화면 누름 막기
var center = new Vector2(0.5f, 0.5f);
overlayText = UiKit.Label(dim, "", 36, Color.white, TextAnchor.MiddleCenter, center, center, new Vector2(0f, 60f), new Vector2(960f, 340f));
overlayText.supportRichText = true;
overlayText.horizontalOverflow = HorizontalWrapMode.Wrap;
overlayButton = OverlayButton(dim, "Retry", UiKit.Red, PressRetry, out overlayButtonLabel);
overlayButton2 = OverlayButton(dim, "Second", UiKit.Dark, PressSecond, out overlayButtonLabel2);
overlayButton2.SetActive(false);
}
static GameObject OverlayButton(Transform parent, string name, Color color, UnityEngine.Events.UnityAction onClick, out Text label)
{
var center = new Vector2(0.5f, 0.5f);
var btn = new GameObject(name, typeof(RectTransform), typeof(Image), typeof(Button));
btn.transform.SetParent(parent, false);
var rt = (RectTransform)btn.transform;
rt.anchorMin = rt.anchorMax = rt.pivot = center;
rt.anchoredPosition = new Vector2(0f, ButtonY);
rt.sizeDelta = ButtonSize;
btn.GetComponent<Image>().color = color;
btn.GetComponent<Button>().onClick.AddListener(onClick);
label = UiKit.Label(rt, "", 34, Color.white, TextAnchor.MiddleCenter, center, center, Vector2.zero, rt.sizeDelta);
label.raycastTarget = false;
return btn;
}
}
}