- Tokens 타입 string? → Dictionary<string,string>? (Go API JSON object 역직렬화 실패 수정) - 409 응답 핸들러 return false → return null (컴파일 에러 수정) - INTO_BOSS_RAID 파티원 각자에게 본인 토큰과 함께 전달 (기존: 파티장에게 N번 중복) - GetPlayer null 체크 추가 (NullReferenceException 방지) - BossId 하드코딩 1 → packet.RaidId 사용 - Player 클래스에 Experience/AttackPower 등 전투 스탯 필드 추가 - ToPlayerInfo에서 새 필드 매핑 추가 - OnIntoChannelParty Nickname을 Session.UserName에서 가져오도록 수정 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
183 lines
5.8 KiB
C#
183 lines
5.8 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json.Serialization;
|
|
using MMOserver.Config;
|
|
using MMOserver.Utils;
|
|
using Serilog;
|
|
|
|
namespace MMOserver.Api;
|
|
|
|
public class RestApi : Singleton<RestApi>
|
|
{
|
|
private readonly HttpClient httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
|
|
|
|
private const int MAX_RETRY = 3;
|
|
private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(1);
|
|
|
|
public RestApi()
|
|
{
|
|
httpClient.DefaultRequestHeaders.Add("X-API-Key", AppConfig.RestApi.ApiKey);
|
|
}
|
|
|
|
// 토큰 검증 - 성공 시 username 반환
|
|
// 401 → 재시도 없이 즉시 null 반환 (토큰 자체가 무효)
|
|
// 타임아웃/네트워크 오류 → 최대 MAX_RETRY회 재시도 후 null 반환
|
|
public async Task<string?> VerifyTokenAsync(string token)
|
|
{
|
|
string url = AppConfig.RestApi.BaseUrl + AppConfig.RestApi.VerifyToken;
|
|
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
|
|
{
|
|
try
|
|
{
|
|
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { token });
|
|
|
|
// 401: 토큰 자체가 무효 → 재시도해도 같은 결과, 즉시 반환
|
|
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
|
{
|
|
Log.Warning("[RestApi] 토큰 인증 실패 (401)");
|
|
return "";
|
|
}
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
AuthVerifyResponse? result = await response.Content.ReadFromJsonAsync<AuthVerifyResponse>();
|
|
return result?.Username;
|
|
}
|
|
catch (Exception ex) when (attempt < MAX_RETRY)
|
|
{
|
|
// 일시적 장애 (타임아웃, 네트워크 오류 등) → 재시도
|
|
Log.Warning("[RestApi] 통신 실패 (시도 {Attempt}/{Max}): {Message}", attempt, MAX_RETRY, ex.Message);
|
|
await Task.Delay(RETRY_DELAY);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// 마지막 시도까지 실패
|
|
Log.Error("[RestApi] 최종 통신 실패 ({Max}회 시도): {Message}", MAX_RETRY, ex.Message);
|
|
}
|
|
}
|
|
|
|
return "";
|
|
}
|
|
|
|
private sealed class AuthVerifyResponse
|
|
{
|
|
[JsonPropertyName("username")]
|
|
public string? Username
|
|
{
|
|
get;
|
|
set;
|
|
}
|
|
}
|
|
|
|
// 레이드 채널 접속 여부 체크
|
|
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
|
|
public async Task<BossRaidResult?> BossRaidAccesssAsync(List<string> userNames, int bossId)
|
|
{
|
|
string url = AppConfig.RestApi.BaseUrl + "/api/internal/bossraid/entry";
|
|
|
|
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
|
|
{
|
|
try
|
|
{
|
|
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { usernames = userNames, bossId });
|
|
|
|
// 401: API 키 인증 실패
|
|
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
|
{
|
|
Log.Warning("[RestApi] 보스 레이드 접속 인증 실패 (401)");
|
|
return null;
|
|
}
|
|
|
|
// 400: 입장 조건 미충족 (레벨 부족 등)
|
|
if (response.StatusCode == HttpStatusCode.BadRequest)
|
|
{
|
|
Log.Warning("[RestApi] 보스 레이드 입장 거절 (400) BossId={BossId}", bossId);
|
|
return null;
|
|
}
|
|
|
|
// 409: 이미 진행 중이거나 슬롯 충돌
|
|
if (response.StatusCode == HttpStatusCode.Conflict)
|
|
{
|
|
Log.Warning("[RestApi] 보스 레이드 충돌 (409) BossId={BossId} - 이미 진행 중이거나 슬롯 없음", bossId);
|
|
return null;
|
|
}
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
BossRaidAccessResponse? raw = await response.Content.ReadFromJsonAsync<BossRaidAccessResponse>();
|
|
if (raw == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
// API 응답 → 도메인 모델 매핑
|
|
return new BossRaidResult
|
|
{
|
|
RoomId = raw.RoomId,
|
|
SessionName = raw.SessionName ?? string.Empty,
|
|
BossId = raw.BossId,
|
|
Players = raw.Players,
|
|
Status = raw.Status ?? string.Empty,
|
|
Tokens = raw.Tokens ?? new()
|
|
};
|
|
}
|
|
catch (Exception ex) when (attempt < MAX_RETRY)
|
|
{
|
|
Log.Warning("[RestApi] 보스 레이드 통신 실패 (시도 {Attempt}/{Max}): {Message}", attempt, MAX_RETRY, ex.Message);
|
|
await Task.Delay(RETRY_DELAY);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Error("[RestApi] 보스 레이드 최종 통신 실패 ({Max}회 시도): {Message}", MAX_RETRY, ex.Message);
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private sealed class BossRaidAccessResponse
|
|
{
|
|
[JsonPropertyName("roomId")]
|
|
public int RoomId
|
|
{
|
|
get;
|
|
set;
|
|
}
|
|
|
|
[JsonPropertyName("sessionName")]
|
|
public string? SessionName
|
|
{
|
|
get;
|
|
set;
|
|
}
|
|
|
|
[JsonPropertyName("bossId")]
|
|
public int BossId
|
|
{
|
|
get;
|
|
set;
|
|
}
|
|
|
|
[JsonPropertyName("players")]
|
|
public List<string> Players
|
|
{
|
|
get;
|
|
set;
|
|
} = new();
|
|
|
|
[JsonPropertyName("status")]
|
|
public string? Status
|
|
{
|
|
get;
|
|
set;
|
|
}
|
|
|
|
[JsonPropertyName("tokens")]
|
|
public Dictionary<string, string>? Tokens
|
|
{
|
|
get;
|
|
set;
|
|
}
|
|
}
|
|
}
|