From 11c35e07ddb48b24667c9ee4650ac013ff49757b Mon Sep 17 00:00:00 2001 From: swrring Date: Tue, 17 Nov 2026 15:56:37 +0900 Subject: [PATCH] =?UTF-8?q?=EC=84=9C=EB=B2=84=20=EC=97=B0=EA=B2=B0=20?= =?UTF-8?q?=E2=80=94=20=EA=B3=B5=EC=A7=80=EC=82=AC=ED=95=AD=20=ED=8C=9D?= =?UTF-8?q?=EC=97=85=20=C2=B7=20=EC=A0=91=EC=86=8D=20=EC=A0=95=EB=B3=B4/?= =?UTF-8?q?=EC=A7=84=ED=96=89=20=EB=8B=A8=EA=B3=84=20=EB=B3=B4=EA=B3=A0(?= =?UTF-8?q?=EA=B2=8C=EC=9E=84=20=EB=A1=9C=EA=B7=B8)=20=C2=B7=20=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=EC=9D=B8=20=ED=99=94=EB=A9=B4=EA=B3=BC=20=EC=98=B5?= =?UTF-8?q?=EC=85=98(=EA=B3=84=EC=A0=95)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 공지사항 팝업(우편함의 「공지사항」) · 우편/공지 글의 언어 칸 - 접속할 때 플랫폼 · 앱 버전 · 지역 · 언어 · 기기 전송 · 진행 단계 보고 ReportStep - 로그인: 저장한 로그인으로 이어 하기 → 없으면 타이틀 위 로그인 화면(게스트 · Google Play · Game Center) · 타이틀은 로그인이 끝나야 넘어감 - 옵션(로비): 소셜 = 로그아웃 / 게스트 = 소셜 계정 연동 + 계정 삭제(확인 문구 입력) · 계정 선택 팝업 - 동시 접속 불가: 다른 기기에서 접속하면 안내 뒤 타이틀로 - 소셜 로그인은 개발용(에디터 · 개발 빌드)만 — 실제 SDK 연동은 추후 - ServerLinkTests 13 통과 + 1 건너뜀 Co-Authored-By: Claude Fable 5.2 --- Assets/Scripts/OutGame/Net/AccountPanel.cs | 223 +++++++++++++ .../Scripts/OutGame/Net/AccountPanel.cs.meta | 2 + Assets/Scripts/OutGame/Net/LoginPanel.cs | 200 ++++++++++++ Assets/Scripts/OutGame/Net/LoginPanel.cs.meta | 2 + Assets/Scripts/OutGame/Net/MailPanel.cs | 8 +- Assets/Scripts/OutGame/Net/NoticePanel.cs | 79 +++++ .../Scripts/OutGame/Net/NoticePanel.cs.meta | 2 + Assets/Scripts/OutGame/Net/ServerClient.cs | 181 ++++++++++- Assets/Scripts/OutGame/Net/ServerSession.cs | 120 ++++++- Assets/Scripts/OutGame/Net/ServerSync.cs | 196 +++++++++++- Assets/Scripts/OutGame/OutGameSession.cs | 14 + Assets/Scripts/OutGame/UI/LobbyScreen.cs | 6 + Assets/Scripts/OutGame/UI/TitleScreen.cs | 4 +- Assets/Tests/PlayMode/ServerLinkTests.cs | 299 ++++++++++++++++++ 14 files changed, 1312 insertions(+), 24 deletions(-) create mode 100644 Assets/Scripts/OutGame/Net/AccountPanel.cs create mode 100644 Assets/Scripts/OutGame/Net/AccountPanel.cs.meta create mode 100644 Assets/Scripts/OutGame/Net/LoginPanel.cs create mode 100644 Assets/Scripts/OutGame/Net/LoginPanel.cs.meta create mode 100644 Assets/Scripts/OutGame/Net/NoticePanel.cs create mode 100644 Assets/Scripts/OutGame/Net/NoticePanel.cs.meta diff --git a/Assets/Scripts/OutGame/Net/AccountPanel.cs b/Assets/Scripts/OutGame/Net/AccountPanel.cs new file mode 100644 index 00000000..6e049cd4 --- /dev/null +++ b/Assets/Scripts/OutGame/Net/AccountPanel.cs @@ -0,0 +1,223 @@ +using System; +using Newtonsoft.Json.Linq; +using UnityEngine; +using UnityEngine.UI; + +namespace TKS.OutGame.Net +{ + /// + /// 옵션 팝업의 계정 칸 — 서버 모드에서만 열린다(로비 「옵션」 버튼). + /// · 소셜 계정으로 로그인한 유저 = 「로그아웃」 → 타이틀의 로그인 화면으로. + /// · 게스트 = 로그아웃 대신 「계정 삭제」(확인 문구 「계정 삭제」를 입력해야 한다 → 데이터 삭제 · 로그인 상태 초기화) + 「소셜 계정 연동」. + /// · 연동하려는 소셜 계정이 이미 다른 게임 계정에 연동돼 있으면 「어느 계정으로 할지」 고르는 팝업(계정 요약 · 데이터가 사라질 수 있다는 안내). + /// (PD 2026-11-17) + /// + public static class AccountPanel + { + /// 유저가 입력해야 하는 확인 문구. + public const string DeletePhrase = "계정 삭제"; + // 서버의 선택 값(연동할 소셜 계정이 이미 다른 계정에 연동돼 있을 때) + public const string KeepCurrent = "keep_current"; + public const string UseExisting = "use_existing"; + const string AlreadyLinked = "OAUTH_ALREADY_LINKED"; + const float Width = 860f; + const float CardH = 430f; + const float CardGap = 16f; + + public static bool Available + { + get { return ServerSync.Instance != null; } + } + + public static void Open(OutGameRoot root) + { + var sync = ServerSync.Instance; + if (sync == null) return; + var content = root.ModalCustom("옵션", 1180f, new OutGameRoot.ModalButton("닫기", UiKit.Dark, null)); + var status = UiKit.Label(content, "계정 정보를 불러오는 중…", 32, UiKit.InkSoft, TextAnchor.UpperLeft, new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(8f, 0f), new Vector2(Width - 16f, 220f), false); + status.horizontalOverflow = HorizontalWrapMode.Wrap; + sync.AccountInfo(r => + { + if (content == null) return; // 받는 사이에 팝업을 닫았다 + if (!r.ok) + { + status.text = "계정 정보를 받지 못했습니다 (" + r.error + ")"; + return; + } + Fill(root, sync, content, status, r); + }); + } + + static void Fill(OutGameRoot root, ServerSync sync, RectTransform content, Text status, ServerResult info) + { + bool guest = info.Str("accountType") == ServerClient.MethodGuest; + string provider = info.Str("provider"); + string login = guest ? "게스트" : SocialSignIn.Label(provider) + (info.Has("socialName") ? " (" + info.Str("socialName") + ")" : ""); + status.text = "닉네임 " + info.Str("nickname") + "\n로그인 계정 " + login + "\n유저 번호 " + info.Str("userId"); + + var top = new Vector2(0.5f, 1f); + float y = -250f; + if (!guest) + { + UiKit.Label(content, "로그아웃하면 타이틀의 로그인 화면으로 돌아갑니다. 같은 소셜 계정으로 다시 로그인하면 이어서 플레이합니다.", 26, UiKit.InkSoft, TextAnchor.UpperLeft, top, top, new Vector2(0f, y), new Vector2(Width - 16f, 80f), false) + .horizontalOverflow = HorizontalWrapMode.Wrap; + UiKit.Btn("Logout", content, "로그아웃", 36, UiKit.Dark, UiKit.White, top, top, new Vector2(0f, y - 100f), new Vector2(560f, 110f), () => + root.Modal("로그아웃", "로그아웃할까요?\n타이틀의 로그인 화면으로 돌아갑니다.", + new OutGameRoot.ModalButton("로그아웃", UiKit.Red, () => sync.Logout(why => root.Toast("로그아웃하지 못했습니다 (" + why + ")"))), + new OutGameRoot.ModalButton("취소", UiKit.Dark, null))); + return; + } + + // 게스트 — 소셜 계정 연동 + UiKit.Label(content, "게스트 계정은 이 기기에서만 이어 할 수 있습니다. 소셜 계정에 연동하면 다른 기기에서도 그 계정으로 로그인해 이어 할 수 있습니다.", 26, UiKit.InkSoft, TextAnchor.UpperLeft, top, top, new Vector2(0f, y), new Vector2(Width - 16f, 80f), false) + .horizontalOverflow = HorizontalWrapMode.Wrap; + y -= 100f; + InputField devId = null; + bool google = SocialSignIn.Available(SocialSignIn.Google), apple = SocialSignIn.Available(SocialSignIn.Apple); + if (SocialSignIn.DevMode && (google || apple)) + { + devId = LoginPanel.Field(content, "DevId", "개발용 — 시험용 소셜 계정 번호", top, new Vector2(0f, y), new Vector2(560f, 84f), SocialSignIn.DevIdMax); + devId.text = sync.Client.LastSocialId; + y -= 104f; + } + if (google) + { + UiKit.Btn("LinkGoogle", content, "Google Play 계정 연동", 34, UiKit.Jade, UiKit.White, top, top, new Vector2(0f, y), new Vector2(560f, 100f), () => Link(root, sync, SocialSignIn.Google, devId != null ? devId.text : "", null)); + y -= 116f; + } + if (apple) + { + UiKit.Btn("LinkApple", content, "Game Center 계정 연동", 34, UiKit.Jade, UiKit.White, top, top, new Vector2(0f, y), new Vector2(560f, 100f), () => Link(root, sync, SocialSignIn.Apple, devId != null ? devId.text : "", null)); + y -= 116f; + } + if (!google && !apple) + { + UiKit.Label(content, "소셜 계정 연동은 준비 중입니다.", 28, UiKit.InkSoft, TextAnchor.MiddleCenter, top, top, new Vector2(0f, y), new Vector2(Width - 16f, 60f), false); + y -= 80f; + } + + // 게스트 — 로그아웃 대신 계정 삭제 + UiKit.Label(content, "게스트 계정은 로그아웃할 수 없습니다(다시 들어올 방법이 없습니다). 계정을 삭제하면 모든 데이터가 지워지고 되돌릴 수 없습니다.", 26, UiKit.InkSoft, TextAnchor.UpperLeft, top, top, new Vector2(0f, y - 20f), new Vector2(Width - 16f, 80f), false) + .horizontalOverflow = HorizontalWrapMode.Wrap; + UiKit.Btn("Delete", content, "계정 삭제", 34, UiKit.Red, UiKit.White, top, top, new Vector2(0f, y - 120f), new Vector2(560f, 100f), () => ConfirmDelete(root, sync)); + } + + /// 계정 삭제 확인 — 유저가 「계정 삭제」를 입력해야 삭제 버튼이 통한다. + public static void ConfirmDelete(OutGameRoot root, ServerSync sync) + { + InputField input = null; + var content = root.ModalCustom("계정 삭제", 760f, + new OutGameRoot.ModalButton("삭제", UiKit.Red, () => + { + if (input == null || !Typed(input.text)) + { + root.Toast("「" + DeletePhrase + "」를 정확히 입력해 주세요"); + return; + } + root.CloseModal(); + sync.DeleteAccount(why => root.Toast("계정을 삭제하지 못했습니다 (" + why + ")")); + }, true), + new OutGameRoot.ModalButton("취소", UiKit.Dark, null)); + var top = new Vector2(0.5f, 1f); + UiKit.Label(content, "계정을 삭제하면 영웅 · 재화 · 진행도 등 모든 데이터가 지워지고 되돌릴 수 없습니다.\n삭제하려면 아래 칸에 「" + DeletePhrase + "」를 입력해 주세요.", 30, UiKit.Ink, TextAnchor.UpperCenter, top, top, new Vector2(0f, -10f), new Vector2(Width - 40f, 220f), false) + .horizontalOverflow = HorizontalWrapMode.Wrap; + input = LoginPanel.Field(content, "Phrase", DeletePhrase, top, new Vector2(0f, -250f), new Vector2(560f, 90f), 20); + } + + /// 입력한 글이 확인 문구와 같은가(앞뒤 빈칸은 봐준다). + public static bool Typed(string text) + { + return (text ?? "").Trim() == DeletePhrase; + } + + /// 소셜 계정 연동 — 이미 다른 게임 계정에 연동된 소셜 계정이면 계정 고르기 팝업을 띄운다. + public static void Link(OutGameRoot root, ServerSync sync, string method, string socialId, string resolve) + { + sync.Link(method, socialId, resolve, r => + { + if (r.ok) + { + root.Toast(r.Str("result") == "switched" ? "기존 연동 계정으로 들어갑니다" : SocialSignIn.Label(method) + " 계정에 연동했습니다"); + if (r.Str("result") != "switched") Open(root); + return; + } + if (r.status == 409 && r.Message == AlreadyLinked) + { + Choose(root, sync, method, socialId, r); + return; + } + root.Toast("연동하지 못했습니다 (" + (string.IsNullOrEmpty(r.Message) ? r.error : r.Message) + ")"); + }); + } + + /// + /// 계정 고르기 — 고른 소셜 계정이 이미 다른 게임 계정에 연동돼 있다. 어느 계정으로 플레이할지 유저가 고른다. + /// · 지금 계정으로 연동 = 기존에 연동돼 있던 계정은 연동이 해제되고, 그 계정의 데이터는 사라질 수 있다. + /// · 기존 연동 계정으로 = 지금 플레이 중인 게스트 계정의 데이터는 사라질 수 있다. + /// + static void Choose(OutGameRoot root, ServerSync sync, string method, string socialId, ServerResult conflict) + { + string name = SocialSignIn.Label(method); + var content = root.ModalCustom("계정 선택", 1320f, new OutGameRoot.ModalButton("취소", UiKit.Dark, null)); + // 내용 칸 높이 = 1320 − 290 = 1030 — 안내 110 + 카드 2장(CardH) + 사이 CardGap 이 그 안에 들어간다 + var top = new Vector2(0.5f, 1f); + UiKit.Label(content, "이 " + name + " 계정은 이미 다른 게임 계정에 연동되어 있습니다.\n어느 계정으로 플레이할지 골라 주세요.", 30, UiKit.Ink, TextAnchor.UpperCenter, top, top, new Vector2(0f, -4f), new Vector2(Width - 20f, 110f), false) + .horizontalOverflow = HorizontalWrapMode.Wrap; + Card(content, -124f, "지금 플레이 중인 계정 (게스트)", conflict.At("current"), + "이 계정을 " + name + " 계정에 연동합니다.\n기존에 연동돼 있던 계정은 연동이 해제되며, 그 계정의 데이터는 사라질 수 있습니다.", + "이 계정으로 연동", () => Confirm(root, "기존에 연동돼 있던 계정은 연동이 해제되고 다시 들어갈 수 없습니다.\n지금 계정으로 연동할까요?", () => Link(root, sync, method, socialId, KeepCurrent))); + Card(content, -124f - CardH - CardGap, "기존에 연동된 계정", conflict.At("existing"), + "기존에 연동된 계정으로 로그인합니다.\n지금 플레이 중인 게스트 계정의 데이터는 사라질 수 있습니다.", + "기존 계정으로 로그인", () => Confirm(root, "지금 플레이 중인 게스트 계정에는 다시 들어갈 수 없습니다.\n기존에 연동된 계정으로 로그인할까요?", () => Link(root, sync, method, socialId, UseExisting))); + } + + static void Confirm(OutGameRoot root, string body, Action yes) + { + root.Modal("확인", body, new OutGameRoot.ModalButton("진행", UiKit.Red, yes), new OutGameRoot.ModalButton("취소", UiKit.Dark, null)); + } + + /// 계정 요약 카드 — 닉네임 · 가입일 · 마지막 접속 · 진행도(마지막으로 깬 스테이지 · 영웅 수) + 고르는 버튼. + static void Card(RectTransform content, float y, string title, JToken account, string warn, string button, Action onClick) + { + var top = new Vector2(0.5f, 1f); + var left = new Vector2(0f, 1f); + var box = UiKit.Box("Card", content, top, top, new Vector2(0f, y), new Vector2(Width - 10f, CardH), UiKit.Paper); // 우편함 줄과 같은 바탕(글자 = 밝은 색) + UiKit.Border(box, UiKit.Line, 2f); + var t = box.transform; + UiKit.Label(t, title, 32, UiKit.Ink, TextAnchor.MiddleLeft, left, left, new Vector2(24f, -14f), new Vector2(Width - 60f, 46f)); + UiKit.Label(t, Summary(account), 26, UiKit.InkSoft, TextAnchor.UpperLeft, left, left, new Vector2(24f, -62f), new Vector2(Width - 60f, 120f), false).horizontalOverflow = HorizontalWrapMode.Wrap; + var w = UiKit.Label(t, warn, 24, UiKit.Ink, TextAnchor.UpperLeft, left, left, new Vector2(24f, -190f), new Vector2(Width - 60f, 110f), false); + w.horizontalOverflow = HorizontalWrapMode.Wrap; + w.supportRichText = true; + UiKit.Btn("Pick", t, button, 32, UiKit.Jade, UiKit.White, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(0f, 18f), new Vector2(520f, 96f), onClick); + } + + /// 연동 응답 안의 계정 요약 글 — which = current(지금 계정) · existing(기존에 연동된 계정). + public static string SummaryOf(ServerResult conflict, string which) + { + return Summary(conflict.At(which)); + } + + /// 계정 요약 글(서버가 준 값만 — 없는 값은 줄을 뺀다). + internal static string Summary(JToken account) + { + var o = account as JObject; + if (o == null) return "계정 정보를 받지 못했습니다"; + string text = "닉네임 " + (string)o["nickname"]; + text += "\n가입 " + Day((string)o["createdAt"]) + " 마지막 접속 " + Day((string)o["lastLoginAt"]); + var s = o["summary"] as JObject; + if (s == null) return text + "\n아직 게임을 시작하지 않은 계정"; + var last = s["lastStage"]; + text += "\n진행 " + (last == null || last.Type == JTokenType.Null ? "깬 스테이지 없음" : "스테이지 " + (string)last + " 까지 (" + (int)(s["clearedStages"] ?? 0) + "곳)"); + text += " 영웅 " + (int)(s["heroes"] ?? 0) + "명"; + return text; + } + + static string Day(string iso) + { + DateTime at; + if (string.IsNullOrEmpty(iso) || !DateTime.TryParse(iso, null, System.Globalization.DateTimeStyles.RoundtripKind, out at)) return "-"; + return at.ToLocalTime().ToString("yyyy-MM-dd"); + } + } +} diff --git a/Assets/Scripts/OutGame/Net/AccountPanel.cs.meta b/Assets/Scripts/OutGame/Net/AccountPanel.cs.meta new file mode 100644 index 00000000..74d35ed9 --- /dev/null +++ b/Assets/Scripts/OutGame/Net/AccountPanel.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c9d22faa6662fe148a78ad9f8ad9524d \ No newline at end of file diff --git a/Assets/Scripts/OutGame/Net/LoginPanel.cs b/Assets/Scripts/OutGame/Net/LoginPanel.cs new file mode 100644 index 00000000..eecc7bb8 --- /dev/null +++ b/Assets/Scripts/OutGame/Net/LoginPanel.cs @@ -0,0 +1,200 @@ +using System; +using UnityEngine; +using UnityEngine.UI; + +namespace TKS.OutGame.Net +{ + /// + /// 기기의 소셜 로그인(구글 플레이 계정 · 애플 게임센터 계정) — 서버에 보낼 증표를 받아 온다. + /// 지금은 **개발용**(에디터 · 개발 빌드)만 있다: 입력한 번호를 그 번호의 소셜 계정으로 쓰는 시험용 증표(dev:번호 — 서버가 시험용 소셜 계정을 받는 설정일 때만 통한다). + /// 실제 기기 연동(구글 플레이 게임즈 · 게임센터 SDK)은 추후 — 그때 SignIn 안만 바꾸면 로그인 · 연동 · 계정 고르기 화면은 그대로다. + /// + public static class SocialSignIn + { + public const string Google = "google"; + public const string Apple = "apple"; + + /// 서버 주소의 플랫폼 이름(google · appstore). + public static string PlatformPath(string method) + { + return method == Apple ? "appstore" : "google"; + } + + /// 화면에 보여 줄 이름. + public static string Label(string method) + { + return method == Google ? "Google Play" : method == Apple ? "Game Center" : "게스트"; + } + + /// 개발용 소셜 로그인을 쓰는가(에디터 · 개발 빌드) — 실제 기기 연동이 들어오기 전까지 출시 빌드에서는 소셜 로그인 버튼이 보이지 않는다. + public static bool DevMode + { + get { return Application.isEditor || Debug.isDebugBuild; } + } + + /// 이 기기에서 그 소셜 로그인을 쓸 수 있는가 — 안드로이드 = 구글 플레이 · iOS = 게임센터 · 에디터 = 둘 다(개발용). + public static bool Available(string method) + { + if (!DevMode) return false; // 실제 기기 연동 전 + if (Application.isEditor) return true; + if (Application.platform == RuntimePlatform.Android) return method == Google; + if (Application.platform == RuntimePlatform.IPhonePlayer) return method == Apple; + return true; + } + + /// 소셜 로그인 — done(증표, 실패 사유). 개발용: 번호(영문 · 숫자 · _ . -)가 비었으면 실패. + public static void SignIn(string method, string devId, Action done) + { + if (!Available(method)) + { + done(null, Label(method) + " 로그인은 준비 중입니다"); + return; + } + string id = (devId ?? "").Trim(); + if (id.Length == 0 || id.Length > DevIdMax || !ValidId(id)) + { + done(null, "시험용 소셜 계정 번호를 넣어 주세요 (영문 · 숫자 · _ . - · " + DevIdMax + "자까지)"); + return; + } + done("dev:" + id, null); + } + + public const int DevIdMax = 40; + + static bool ValidId(string id) + { + foreach (char c in id) + if (!(char.IsLetterOrDigit(c) && c < 128) && c != '_' && c != '.' && c != '-') return false; + return true; + } + } + + /// + /// 로그인 화면 — 타이틀 위에 뜬다(접속 일꾼 ServerSync 가 띄운다). 게스트로 시작 · 소셜 계정으로 로그인. + /// 기기에 저장한 로그인이 있으면 이 화면 없이 마지막에 로그인한 계정으로 바로 들어간다 — 이 화면은 처음 실행 · 로그아웃 · 계정 삭제 · 세션이 끊긴 뒤에만 뜬다. + /// 가끔만 뜨는 화면이라 자기 캔버스 1개(사건 때만 바뀌는 층)에 그린다. + /// + public class LoginPanel : MonoBehaviour + { + // 접속 안내(990) 바로 아래 · 타이틀 전환(960) 위 + const int Order = 985; + const float Plane = 0.32f; + const float PanelW = 880f; + const float ButtonW = 720f; + const float ButtonH = 120f; + const float Gap = 24f; + + public static LoginPanel Current { get; private set; } + + /// 안내 글(로그인 실패 사유 · 세션이 끊긴 이유) — 없으면 "". + public string Notice { get; private set; } + public InputField DevId { get; private set; } + + Action onChoose; + + /// 로그인 화면을 띄운다. onChoose(방식, 시험용 소셜 계정 번호) — 방식 = guest · google · apple. + public static LoginPanel Show(Transform parent, Camera cam, string lastMethod, string lastId, string notice, Action onChoose) + { + Close(); + var go = new GameObject("LoginPanel"); + go.transform.SetParent(parent, false); + var p = go.AddComponent(); + p.onChoose = onChoose; + p.Notice = notice ?? ""; + p.Build(cam, lastMethod, lastId); + Current = p; + return p; + } + + public static void Close() + { + if (Current == null) return; + Destroy(Current.gameObject); + Current = null; + } + + void OnDestroy() + { + if (Current == this) Current = null; + } + + /// 고름(버튼 · 테스트) — devId 를 주지 않으면 입력 칸의 값을 쓴다. + public void Choose(string method, string devId = null) + { + if (onChoose == null) return; + var done = onChoose; + onChoose = null; // 한 번만 + done(method, devId ?? (DevId != null ? DevId.text : "")); + } + + void Build(Camera cam, string lastMethod, string lastId) + { + UiLayer.Root(gameObject, cam, Order, Plane, OutGameRoot.Reference, UiRate.Event); + var dim = UiKit.Fill("Dim", transform); + var dimImg = dim.gameObject.AddComponent(); + dimImg.color = new Color(0f, 0f, 0f, 0.6f); + dimImg.raycastTarget = true; // 아래 화면(타이틀) 누름 막기 + + bool google = SocialSignIn.Available(SocialSignIn.Google); + bool apple = SocialSignIn.Available(SocialSignIn.Apple); + bool dev = SocialSignIn.DevMode && (google || apple); + int buttons = 1 + (google ? 1 : 0) + (apple ? 1 : 0); + float noticeH = Notice.Length > 0 ? 130f : 0f; + float devH = dev ? 150f : 0f; + float h = 210f + noticeH + buttons * (ButtonH + Gap) + devH + 90f; + + var center = new Vector2(0.5f, 0.5f); + var top = new Vector2(0.5f, 1f); + var panel = UiKit.Box("Panel", dim, center, center, Vector2.zero, new Vector2(PanelW, h), UiKit.Paper); + panel.raycastTarget = true; + UiKit.Border(panel, UiKit.Line, 4f); + var pt = panel.transform; + UiKit.Label(pt, "로그인", 52, UiKit.Ink, TextAnchor.MiddleCenter, top, top, new Vector2(0f, -36f), new Vector2(PanelW - 80f, 70f)); + string last = string.IsNullOrEmpty(lastMethod) ? "게임을 시작할 계정을 골라 주세요" : "마지막 로그인: " + SocialSignIn.Label(lastMethod); + UiKit.Label(pt, last, 28, UiKit.InkSoft, TextAnchor.MiddleCenter, top, top, new Vector2(0f, -116f), new Vector2(PanelW - 80f, 44f), false); + float y = -190f; + if (Notice.Length > 0) + { + var n = UiKit.Label(pt, Notice, 28, UiKit.Red, TextAnchor.MiddleCenter, top, top, new Vector2(0f, y), new Vector2(PanelW - 100f, noticeH - 20f), false); + n.horizontalOverflow = HorizontalWrapMode.Wrap; + y -= noticeH; + } + y = AddButton(pt, "Guest", "게스트로 시작", UiKit.Dark, y, () => Choose(ServerClient.MethodGuest)); + if (google) y = AddButton(pt, "Google", "Google Play 로 로그인", UiKit.Jade, y, () => Choose(SocialSignIn.Google)); + if (apple) y = AddButton(pt, "Apple", "Game Center 로 로그인", UiKit.Jade, y, () => Choose(SocialSignIn.Apple)); + if (dev) + { + UiKit.Label(pt, "개발용 — 시험용 소셜 계정 번호(같은 번호 = 같은 계정)", 24, UiKit.InkSoft, TextAnchor.MiddleLeft, top, top, new Vector2(0f, y - 4f), new Vector2(ButtonW, 36f), false); + DevId = Field(pt, "DevId", "예: tester1", top, new Vector2(0f, y - 46f), new Vector2(ButtonW, 84f), SocialSignIn.DevIdMax); + DevId.text = lastId ?? ""; + y -= devH; + } + UiKit.Label(pt, "게스트 계정은 이 기기에서만 이어 할 수 있습니다. 옵션에서 소셜 계정에 연동하면 다른 기기에서도 이어 할 수 있습니다.", 22, UiKit.InkSoft, TextAnchor.UpperCenter, top, top, new Vector2(0f, y - 4f), new Vector2(PanelW - 100f, 70f), false) + .horizontalOverflow = HorizontalWrapMode.Wrap; + } + + static float AddButton(Transform parent, string name, string label, Color color, float y, Action onClick) + { + var top = new Vector2(0.5f, 1f); + UiKit.Btn(name, parent, label, 38, color, UiKit.White, top, top, new Vector2(0f, y), new Vector2(ButtonW, ButtonH), onClick); + return y - ButtonH - Gap; + } + + /// 한 줄 입력 칸(흰 상자 + 테두리 · 우편함의 쿠폰 입력과 같은 모양). + internal static InputField Field(Transform parent, string name, string hint, Vector2 anchor, Vector2 pos, Vector2 size, int limit) + { + var box = UiKit.Box(name, parent, anchor, anchor, pos, size, UiKit.White); + box.raycastTarget = true; + UiKit.Border(box, UiKit.Line, 2f); + var text = UiKit.FillLabel(box.transform, "", 34, UiKit.Dark, TextAnchor.MiddleLeft, false, 20f); // 흰 칸 위 = 어두운 글자 + text.supportRichText = false; + var ph = UiKit.FillLabel(box.transform, hint, 30, UiKit.InkSoft, TextAnchor.MiddleLeft, false, 20f); + var input = box.gameObject.AddComponent(); + input.textComponent = text; + input.placeholder = ph; + input.characterLimit = limit; + input.lineType = InputField.LineType.SingleLine; + return input; + } + } +} diff --git a/Assets/Scripts/OutGame/Net/LoginPanel.cs.meta b/Assets/Scripts/OutGame/Net/LoginPanel.cs.meta new file mode 100644 index 00000000..e268277c --- /dev/null +++ b/Assets/Scripts/OutGame/Net/LoginPanel.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4f93dd35b3db9f443891632080748f7f \ No newline at end of file diff --git a/Assets/Scripts/OutGame/Net/MailPanel.cs b/Assets/Scripts/OutGame/Net/MailPanel.cs index 58fdf0a3..4cc18ebf 100644 --- a/Assets/Scripts/OutGame/Net/MailPanel.cs +++ b/Assets/Scripts/OutGame/Net/MailPanel.cs @@ -22,7 +22,7 @@ namespace TKS.OutGame namespace TKS.OutGame.Net { /// - /// 우편함 팝업 — 목록(받기 · 모두 받기) + 쿠폰 입력. 서버 모드에서만 열린다(로비 「우편」 버튼). + /// 우편함 팝업 — 목록(받기 · 모두 받기) + 쿠폰 입력 + 아래 「공지사항」 버튼(Net/NoticePanel). 서버 모드에서만 열린다(로비 「우편」 버튼). /// 우편은 운영툴에서 만든다(개별 · 전체 · 쿠폰). 받은 우편은 목록에서 빠진다. /// public static class MailPanel @@ -33,7 +33,9 @@ namespace TKS.OutGame.Net public static void Open(OutGameRoot root) { - var content = root.ModalCustom("우편", 1500f, new OutGameRoot.ModalButton("닫기", UiKit.Dark, null)); + var content = root.ModalCustom("우편", 1500f, + new OutGameRoot.ModalButton("공지사항", UiKit.Jade, () => NoticePanel.Open(root)), + new OutGameRoot.ModalButton("닫기", UiKit.Dark, null)); var status = UiKit.Label(content, "우편을 불러오는 중…", 32, UiKit.InkSoft, TextAnchor.MiddleLeft, new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(8f, 0f), new Vector2(560f, 64f), false); Coupon(root, content); root.Session.MailListAsync((list, why) => @@ -92,7 +94,7 @@ namespace TKS.OutGame.Net var box = UiKit.Box("Coupon", content, new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(Width - 260f, CouponH), UiKit.White); box.raycastTarget = true; UiKit.Border(box, UiKit.Line, 2f); - var text = UiKit.FillLabel(box.transform, "", 34, UiKit.Ink, TextAnchor.MiddleLeft, false, 20f); + var text = UiKit.FillLabel(box.transform, "", 34, UiKit.Dark, TextAnchor.MiddleLeft, false, 20f); // 흰 칸 위 = 어두운 글자 text.supportRichText = false; var hint = UiKit.FillLabel(box.transform, "쿠폰 코드", 30, UiKit.InkSoft, TextAnchor.MiddleLeft, false, 20f); var input = box.gameObject.AddComponent(); diff --git a/Assets/Scripts/OutGame/Net/NoticePanel.cs b/Assets/Scripts/OutGame/Net/NoticePanel.cs new file mode 100644 index 00000000..96691373 --- /dev/null +++ b/Assets/Scripts/OutGame/Net/NoticePanel.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; + +namespace TKS.OutGame +{ + /// 공지 1건(화면 표시용) — 서버가 내려 준 공지를 세션(Net/ServerSession)이 이 모양으로 바꿔 준다(글은 게임 언어 칸 · 없으면 한국어). + public class NoticeItem + { + public int id; + public string title = ""; + public string body = ""; + /// 보이기 시작 · 끝(UTC). + public DateTime startAt; + public DateTime endAt; + } +} + +namespace TKS.OutGame.Net +{ + /// + /// 공지사항 팝업 — 운영툴에서 등록한 공지 가운데 지금 기간 안의 것을 최근 것부터 보여 준다. 서버 모드에서만 열린다(우편함의 「공지사항」 버튼). + /// 줄을 누르면 그 공지의 전체 글을 띄운다. + /// + public static class NoticePanel + { + const float Width = 860f; + const float RowH = 250f; + + public static void Open(OutGameRoot root) + { + var content = root.ModalCustom("공지사항", 1500f, + new OutGameRoot.ModalButton("우편", UiKit.Jade, () => MailPanel.Open(root)), + new OutGameRoot.ModalButton("닫기", UiKit.Dark, null)); + var status = UiKit.Label(content, "공지를 불러오는 중…", 32, UiKit.InkSoft, TextAnchor.MiddleLeft, new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(8f, 0f), new Vector2(Width - 16f, 64f), false); + root.Session.NoticeListAsync((list, why) => + { + if (content == null) return; // 받는 사이에 팝업을 닫았다 + if (list == null) + { + status.text = why; + return; + } + Fill(root, content, status, list); + }); + } + + static void Fill(OutGameRoot root, RectTransform content, Text status, List list) + { + status.text = list.Count == 0 ? "지금 올라온 공지가 없습니다" : "공지 " + list.Count + "건 · 누르면 전체 글이 보입니다"; + if (list.Count == 0) return; + + ScrollRect sr; + var grid = UiKit.ScrollGrid("Notices", content, 0f, 0f, 80f, 0f, new Vector2(Width, RowH), new Vector2(0f, 12f), 1, out sr); + foreach (var n in list) + { + var notice = n; + var cell = UiKit.Cell(grid, "Notice_" + notice.id, UiKit.Paper, () => Detail(root, notice)); + UiKit.Border(cell, UiKit.Line, 2f); + // 위에서부터: 제목 · 본문 앞부분(넘치면 자름) · 기간 + UiKit.Label(cell.transform, notice.title, 36, UiKit.Ink, TextAnchor.UpperLeft, new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(20f, -14f), new Vector2(Width - 40f, 50f)).verticalOverflow = VerticalWrapMode.Truncate; + UiKit.Label(cell.transform, notice.body, 28, UiKit.InkSoft, TextAnchor.UpperLeft, new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(20f, -70f), new Vector2(Width - 40f, 130f), false).verticalOverflow = VerticalWrapMode.Truncate; + UiKit.Label(cell.transform, Period(notice), 22, UiKit.InkSoft, TextAnchor.LowerLeft, new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(20f, 10f), new Vector2(Width - 40f, 30f), false); + } + } + + static string Period(NoticeItem n) + { + return n.startAt.ToLocalTime().ToString("M월 d일 HH:mm") + " ~ " + n.endAt.ToLocalTime().ToString("M월 d일 HH:mm"); + } + + /// 공지 1건의 전체 글 — 닫으면 목록으로 돌아간다. + static void Detail(OutGameRoot root, NoticeItem n) + { + root.Modal(n.title, n.body + "\n\n" + Period(n) + "", new OutGameRoot.ModalButton("목록", UiKit.Dark, () => Open(root))); + } + } +} diff --git a/Assets/Scripts/OutGame/Net/NoticePanel.cs.meta b/Assets/Scripts/OutGame/Net/NoticePanel.cs.meta new file mode 100644 index 00000000..40a7ee64 --- /dev/null +++ b/Assets/Scripts/OutGame/Net/NoticePanel.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f032b3be0e7adca40bf25664aff620f9 \ No newline at end of file diff --git a/Assets/Scripts/OutGame/Net/ServerClient.cs b/Assets/Scripts/OutGame/Net/ServerClient.cs index 41f27572..99efc194 100644 --- a/Assets/Scripts/OutGame/Net/ServerClient.cs +++ b/Assets/Scripts/OutGame/Net/ServerClient.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; @@ -81,7 +82,8 @@ namespace TKS.OutGame.Net /// /// 서버와 HTTP 로 말하는 가장 아래 층 — 주소 붙이기 · 로그인 증표 · 응답 해석만 한다(게임 규칙은 모른다). - /// 로그인 = 기기에 저장한 재발급 증표로 이어 하기 → 없거나 서버가 받지 않으면 새 게스트 계정. + /// 로그인 = 게스트(새 계정) 또는 소셜 계정(구글 플레이 · 게임센터) · 다음부터는 기기에 저장한 재발급 증표로 이어 한다(앱을 켤 때 = 새 세션). + /// 한 계정은 한 기기에서만 접속한다 — 다른 기기에서 접속하면 서버가 이쪽 증표를 못 쓰게 하고(401 SESSION_REPLACED), 그 사실을 LostReason 으로 알린다. /// public class ServerClient { @@ -92,13 +94,38 @@ namespace TKS.OutGame.Net string accessToken; string refreshToken; - public ServerClient(string baseUrl, int timeoutSec, bool persist) + // 서버가 「이 세션은 끝났다」고 알리는 이유 코드 + public const string LostReplaced = "SESSION_REPLACED"; // 다른 기기에서 접속(또는 로그아웃 · 연동 변경) + public const string LostDeleted = "ACCOUNT_DELETED"; + public const string LostExpired = "SESSION_EXPIRED"; // 증표를 다시 받지 못함 + public const string MethodGuest = "guest"; + // 계정 삭제 요청의 확인 값 — 유저가 화면에서 확인 문구를 입력한 뒤에만 보낸다(서버 규칙과 같은 값) + const string DeleteConfirm = "DELETE"; + + /// 세션을 잃은 이유(null = 정상) — 값이 있으면 다시 로그인해야 한다. + public string LostReason { get; private set; } + /// 지금 세션의 로그인 방식(guest · google · apple). + public string Method { get; private set; } + + // 기기에 저장하지 않는 모드(테스트)의 임시 보관 — 씬을 다시 열어도 남는다(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) { @@ -110,6 +137,64 @@ namespace TKS.OutGame.Net 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) { @@ -123,10 +208,25 @@ namespace TKS.OutGame.Net 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; + 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) yield break; + if (!again.ok) + { + if (!again.network) LostReason = LostExpired; // 재발급 증표도 받아 주지 않는다 = 다시 로그인해야 한다 + yield break; + } } } @@ -182,35 +282,88 @@ namespace TKS.OutGame.Net } } - /// 로그인 — 저장한 증표로 이어 하기 → 서버가 받지 않으면 새 게스트 계정. + /// 테스트용 자동 로그인 — 저장한 증표가 있으면 이어 하기 → 없거나 서버가 받지 않으면 새 게스트 계정(로그인 화면 없음). public IEnumerator Login(int gameId, ServerResult res) { - if (persist) refreshToken = PlayerPrefs.GetString(RefreshKey(baseUrl), ""); - if (!string.IsNullOrEmpty(refreshToken)) + if (HasSaved) { - yield return Refresh(res); + yield return Resume(res); if (res.ok || res.network) 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); + 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); } 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); + if (res.ok) Store(res, null, null); } - void Store(ServerResult res) + /// 받은 증표를 쓰기 시작하고 기기에 저장한다. method = null 이면 서버가 알려 준 방식(게스트 · 소셜 서비스)을 쓴다. + void Store(ServerResult res, string method, string socialId) { accessToken = res.Str("accessToken"); refreshToken = res.Str("refreshToken"); - if (!persist) return; - PlayerPrefs.SetString(RefreshKey(baseUrl), refreshToken); - PlayerPrefs.Save(); + LostReason = 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); } } } diff --git a/Assets/Scripts/OutGame/Net/ServerSession.cs b/Assets/Scripts/OutGame/Net/ServerSession.cs index a631cbc5..17eae6c5 100644 --- a/Assets/Scripts/OutGame/Net/ServerSession.cs +++ b/Assets/Scripts/OutGame/Net/ServerSession.cs @@ -31,7 +31,7 @@ namespace TKS.OutGame.Net const string RewardGoods = "goods"; const string RewardGear = "gear"; const string RewardChest = "chest"; - // 우편 글의 언어 칸 + // 서버 메시지(우편 · 공지사항) 글의 언어 칸 — 게임에 언어 설정이 생기면 그 값으로 바꾼다(서버는 ko · en · ja · zh-Hans · zh-Hant 칸을 준다) const string MailLang = "ko"; // 우편 보상에 보여 줄 재화 이름(묶음 → 이름) static readonly Dictionary WalletName = new Dictionary @@ -104,14 +104,84 @@ namespace TKS.OutGame.Net } } - /// 접속할 때의 계정 조회 주소 — 기기 시간대를 실어 보낸다(서버는 계정을 만드는 순간에만 이 값을 계정에 고정한다). + /// + /// 접속할 때의 계정 조회 주소 — 기기 시간대와 접속 정보를 실어 보낸다. + /// 서버는 시간대를 계정을 만드는 순간에만 계정에 고정하고, 접속 정보는 접속 기록 · 가입 정보 · 모든 게임 로그의 앱 버전/플랫폼 칸에 쓴다. + /// internal static string AccountPath() { - if (ServerLink.SkipSignupTimezone) return "/tks/account"; + if (ServerLink.SkipSignupTimezone) return "/tks/account?" + ClientQuery(); string zone; int offsetMin; DeviceTimezone(out zone, out offsetMin); - return "/tks/account?zone=" + Esc(zone) + "&offsetMin=" + offsetMin.ToString(CultureInfo.InvariantCulture); + return "/tks/account?zone=" + Esc(zone) + "&offsetMin=" + offsetMin.ToString(CultureInfo.InvariantCulture) + "&" + ClientQuery(); + } + + // ---------- 접속 정보 (게임 로그 — 서버가 접속 기록 · 가입 정보 · 로그의 앱 버전/플랫폼 칸에 쓴다) ---------- + + // 서버가 받는 길이(넘으면 서버가 그 칸을 비운다) + const int PlatformMax = 12; + const int LangMax = 12; + const int DeviceMax = 80; + + /// 접속 정보 — 플랫폼 · 앱 버전 · 지역(ISO 두 글자) · 언어 · 기기 모델. 구하지 못한 값은 비워 보낸다(서버가 빈 값으로 둔다 · 지역이 비면 서버가 시간대로 추정한다). + public static string ClientQuery() + { + return "platform=" + Esc(PlatformName()) + "&ver=" + Esc(Application.version ?? "") + "&country=" + Esc(DeviceCountry()) + + "&lang=" + Esc(DeviceLanguage()) + "&device=" + Esc(Cut(SystemInfo.deviceModel ?? "", DeviceMax)); + } + + static string Cut(string s, int max) + { + return s.Length <= max ? s : s.Substring(0, max); + } + + /// 플랫폼 이름 — android · ios · editor · 그 밖은 Unity 의 플랫폼 이름(소문자). + static string PlatformName() + { + if (Application.isEditor) return "editor"; + switch (Application.platform) + { + case RuntimePlatform.Android: return "android"; + case RuntimePlatform.IPhonePlayer: return "ios"; + default: return Cut(Application.platform.ToString().ToLowerInvariant(), PlatformMax); + } + } + + /// 기기 지역(ISO 두 글자) — 구하지 못하면 빈 값. + static string DeviceCountry() + { + try + { + var code = RegionInfo.CurrentRegion.TwoLetterISORegionName ?? ""; + return code.Length == 2 && char.IsLetter(code[0]) && char.IsLetter(code[1]) ? code.ToUpperInvariant() : ""; + } + catch (Exception) + { + return ""; + } + } + + /// 기기 언어 — 문화권의 두 글자 언어 코드(ko · en …) · 없으면 Unity 의 시스템 언어 이름. + static string DeviceLanguage() + { + try + { + var code = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName ?? ""; + if (code.Length == 2 && code != "iv") return code.ToLowerInvariant(); // iv = 문화권을 모르는 기기 + } + catch (Exception) + { + // 아래 값으로 + } + return Cut(Application.systemLanguage.ToString(), LangMax); + } + + /// 진행 단계 보고(튜토리얼 …) — 서버의 단계 표에 있는 이름만 남는다. 유저마다 처음 한 번만 남으므로 여러 번 보내도 된다. 거절돼도 게임은 그대로 진행한다. + public override void ReportStep(string step) + { + if (string.IsNullOrEmpty(step)) return; + Sync.Post("POST", "/tks/funnel", () => Json(o => { o["step"] = step; }), soft: true); } /// @@ -918,6 +988,26 @@ namespace TKS.OutGame.Net return long.TryParse(t.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out n) ? n : 0; } + // ---------- 공지사항 ---------- + + /// 공지 목록 — 글은 게임 언어 칸을 고르고(없으면 처음 있는 글 = 한국어) 화면용 모양으로 바꾼다. + public override void NoticeListAsync(Action, string> done) + { + Sync.Post("GET", "/tks/notices", null, + r => + { + var list = new List(); + foreach (var n in r.At("notices") as JArray ?? new JArray()) + list.Add(new NoticeItem + { + id = Int(n["id"]), title = Localized(n["title"]), body = Localized(n["body"]), + startAt = SaveStore.ParseIso((string)n["startAt"], DateTime.MinValue), endAt = SaveStore.ParseIso((string)n["endAt"], DateTime.MinValue), + }); + done(list, null); + }, + r => done(null, Refused(r)), true, false, true); + } + // ---------- 4단계: 우편 · 쿠폰 ---------- public override bool MailAvailable @@ -1198,10 +1288,30 @@ namespace TKS.OutGame.Net /// 서버 연결 테스트 전용 — 씬을 열기 전에 부른다. 끝나면 ClearForce. public static void ForceForTest(string url, int gameId) { + ServerClient.ClearMemory(); // 테스트마다 새 계정으로 시작한다 ServerConfig.ForceForTest(url, gameId); Apply(); } + /// 서버 연결 테스트 전용 — 켜면 테스트에서도 로그인 화면을 거친다(기본 = 화면 없이 게스트 자동 로그인). ClearForce 가 되돌린다. + public static bool LoginUi; + + /// 로그인 화면 없이 자동으로 로그인하는가(테스트 모드의 기본). + public static bool AutoLogin + { + get { return ServerConfig.Forced && !LoginUi; } + } + + /// + /// 타이틀부터 다시 시작한다(로그아웃 · 계정 삭제 · 다른 기기에서 접속해 세션이 끊김 · 기존 연동 계정으로 들어감) — + /// 지금 씬을 다시 열어 접속 일꾼이 새로 로그인하게 한다(저장한 증표가 없으면 로그인 화면). + /// + public static void Restart() + { + if (ServerSync.Instance != null) UnityEngine.Object.Destroy(ServerSync.Instance.gameObject); + UnityEngine.SceneManagement.SceneManager.LoadScene(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name); + } + /// /// 서버 연결 테스트 전용 — 켜면 접속할 때 기기 시간대를 보내지 않는다(시간대가 없는 기존 계정이 접속한 경우를 만든다). ClearForce 가 되돌린다. /// @@ -1210,6 +1320,8 @@ namespace TKS.OutGame.Net public static void ClearForce() { SkipSignupTimezone = false; + LoginUi = false; + ServerClient.ClearMemory(); ServerConfig.ClearForce(); Apply(); } diff --git a/Assets/Scripts/OutGame/Net/ServerSync.cs b/Assets/Scripts/OutGame/Net/ServerSync.cs index 9aebe1ac..9fa3f5c5 100644 --- a/Assets/Scripts/OutGame/Net/ServerSync.cs +++ b/Assets/Scripts/OutGame/Net/ServerSync.cs @@ -13,6 +13,7 @@ namespace TKS.OutGame.Net /// 3. 맞춤: 보낼 것이 없어지면 서버의 계정 상태를 다시 받아 기기 값을 덮는다 — 서버가 정본이다. /// 4. 거절: 서버가 요청을 받아 주지 않으면(기기와 서버가 어긋남) 남은 요청을 버리고 서버 상태로 되돌린다. /// 5. 끊김: 연결 문제는 몇 번 조용히 다시 보내고, 그래도 안 되면 화면을 막고 「다시 시도」를 받는다. + /// 6. 로그인: 저장한 증표로 이어 하기 → 없으면 로그인 화면(게스트 · 소셜). 다른 기기에서 같은 계정으로 접속하면 이쪽은 안내 뒤 타이틀로 돌아간다. /// public class ServerSync : MonoBehaviour { @@ -36,6 +37,13 @@ namespace TKS.OutGame.Net { get { return overlay != null && overlay.activeSelf; } } + /// 세션을 잃어(다른 기기에서 접속 등) 타이틀로 돌아가는 안내가 떴는가. + public bool Kicked { get; private set; } + /// 화면을 막는 안내의 글(테스트 · 확인용). + public string OverlayMessage + { + get { return overlayText != null && Blocking ? overlayText.text : ""; } + } class Item { @@ -71,6 +79,7 @@ namespace TKS.OutGame.Net GameObject overlay; Text overlayText; GameObject overlayButton; + Text overlayButtonLabel; internal static ServerSync Create(ServerSession session) { @@ -145,12 +154,13 @@ namespace TKS.OutGame.Net continue; } - yield return Client.Login(ServerConfig.GameId, r); + yield return Authenticate(r); if (!r.ok) { yield return AskRetry("로그인하지 못했습니다", r); continue; } + ShowOverlay("서버에 접속하는 중…", false); // 기기 시간대를 실어 보낸다 — 새 계정이면 서버가 이때 계정에 고정한다(일일 초기화 = 그 나라 0시) yield return Client.Send("GET", ServerSession.AccountPath(), null, true, r); @@ -166,6 +176,176 @@ namespace TKS.OutGame.Net } } + // ---------- 로그인 ---------- + + /// + /// 로그인 — 기기에 저장한 증표가 있으면 그 계정으로 이어 하고(마지막에 로그인한 계정), 없거나 서버가 받지 않으면 로그인 화면을 띄운다. + /// 로그인 화면 = 게스트로 시작 · 소셜 계정(구글 플레이 · 게임센터)으로 로그인. 끝나면 r.ok (연결 문제면 r.network). + /// + IEnumerator Authenticate(ServerResult r) + { + if (ServerLink.AutoLogin) + { + yield return Client.Login(ServerConfig.GameId, r); // 테스트: 화면 없이 이어 하기 → 없으면 새 게스트 + yield break; + } + string notice = null; + if (Client.HasSaved) + { + yield return Client.Resume(r); + if (r.ok || r.network) 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; + 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) yield break; + notice = "로그인하지 못했습니다 (" + (string.IsNullOrEmpty(r.Message) ? r.error : r.Message) + ")"; + } + } + + /// + /// 세션을 잃었다(다른 기기에서 이 계정으로 접속 · 삭제된 계정 · 증표 만료) — 줄 선 요청을 버리고 안내한 뒤 타이틀(로그인 화면)로 돌아간다. + /// 한 계정은 한 기기에서만 접속한다(PD 2026-11-17). + /// + 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 ? "삭제된 계정입니다." + : "로그인 정보가 만료되었습니다."; + retryPressed = false; + ShowOverlay(msg + "\n확인을 누르면 타이틀 화면으로 돌아갑니다", true, "확인"); + while (!retryPressed) yield return null; + ServerLink.Restart(); + while (true) yield return null; // 씬이 바뀔 때까지 + } + + // ---------- 계정 (옵션 화면이 부른다) ---------- + + /// 지금 로그인한 계정의 로그인 정보(게스트인가 · 어느 소셜 계정인가). + public void AccountInfo(Action done) + { + Post("GET", "/auth/session", null, done, done, false, false, true); + } + + /// 로그아웃(소셜 계정) → 타이틀의 로그인 화면으로. 실패하면 fail(이유). + public void Logout(Action fail) + { + StartCoroutine(Leave(false, fail)); + } + + /// 계정 삭제(게스트) → 서버가 데이터를 지우고, 기기의 로그인 상태를 초기화한 뒤 타이틀의 로그인 화면으로. + public void DeleteAccount(Action fail) + { + StartCoroutine(Leave(true, fail)); + } + + IEnumerator Leave(bool delete, Action fail) + { + while (Busy) yield return null; // 줄 선 요청을 먼저 다 보낸다 + ShowOverlay(delete ? "계정을 삭제하는 중…" : "로그아웃하는 중…", false); + var r = new ServerResult(); + if (delete) yield return Client.DeleteAccount(r); + else yield return Client.Logout(r); + HideOverlay(); + if (!r.ok) + { + if (fail != null) fail(r.network ? "서버와 연결되지 않았습니다" : r.Message); + yield break; + } + Ready = false; + ServerLink.Restart(); + } + + /// + /// 게스트 계정을 소셜 계정에 연동. done(r): r.ok = 끝(연동됨 · 또는 기존 계정으로 들어감 → 타이틀로 다시 시작) · + /// r.status 409 = 그 소셜 계정이 이미 다른 게임 계정에 연동돼 있다(r 에 current · existing 요약) → 유저가 고른 뒤 resolve 를 붙여 다시 부른다 · 그 밖 = 실패. + /// + public void Link(string method, string socialId, string resolve, Action done) + { + StartCoroutine(LinkRoutine(method, socialId, resolve, done)); + } + + IEnumerator LinkRoutine(string method, string socialId, string resolve, Action 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() @@ -190,6 +370,11 @@ namespace TKS.OutGame.Net } waitSince = -1f; HideOverlay(); + if (Client.LostReason != null) + { + yield return Kick(); // 다른 기기에서 접속했다 등 — 타이틀로 돌아간다 + yield break; + } queue.Dequeue(); sending = false; @@ -237,6 +422,11 @@ namespace TKS.OutGame.Net { var r = new ServerResult(); yield return Client.Send("GET", "/tks/account", null, true, r); + if (Client.LostReason != null) + { + yield return Kick(); + yield break; + } if (!r.ok) { reconcileAt = Time.unscaledTime + Mathf.Max(1f, ServerConfig.ReconcileDelay) * 3f; // 조금 뒤에 다시 @@ -276,11 +466,12 @@ namespace TKS.OutGame.Net retryPressed = true; } - void ShowOverlay(string msg, bool button) + void ShowOverlay(string msg, bool button, string buttonLabel = "다시 시도") { if (overlay == null) BuildOverlay(); overlayText.text = msg; overlayButton.SetActive(button); + if (overlayButtonLabel != null) overlayButtonLabel.text = buttonLabel; overlay.SetActive(true); } @@ -316,6 +507,7 @@ namespace TKS.OutGame.Net btn.GetComponent