ThreeKingdomsSlingshot/Assets/Scripts/OutGame/Boot/CdnDownloader.cs

232 lines
8.0 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace TKS.OutGame
{
/// <summary>CDN 목록 파일(JSON) — {"version":"…","files":[{"path":"a/b.bundle","size":123}]} · path = CDN 주소 아래 상대 경로(= 받아 둘 로컬 상대 경로).</summary>
[Serializable]
public class CdnManifest
{
public string version;
public List<CdnFile> files = new List<CdnFile>();
}
[Serializable]
public class CdnFile
{
public string path;
public long size;
}
/// <summary>
/// CDN 리소스 확인·받기(PD 2026-11-16 「스플래쉬로 회사 CI 를 먼저 노출하고, CDN 파일이 존재할 경우 CDN 리소스 체크 후 타이틀 화면으로 전환」).
/// 확인 = CDN 주소/목록 파일을 받아 로컬(persistentDataPath/cdn)에 없거나 크기가 다른 파일만 받을 목록에 넣음.
/// CDN 주소가 비었거나 목록 파일이 없으면(404 · file:// 파일 없음) = 「CDN 파일 없음」 → 받을 것 없음 → 바로 타이틀.
/// 확인 자체가 실패(네트워크)하면 = 로컬에 있는 것으로 진행(경고 로그 · 오프라인에서도 게임 시작) · 받는 중 실패 = Error → BootFlow 가 표 retry 초 뒤 Begin() 으로 다시(받은 파일은 크기가 맞으면 건너뜀).
/// 값 = 표 Resources/UI/boot_flow.csv 의 cdn 줄(C45) · 받은 리소스를 게임이 읽는 부분은 CDN 콘텐츠가 정해진 뒤 연결.
/// </summary>
public class CdnDownloader : IResourceDownloader
{
readonly string baseUrl;
readonly string manifestName;
readonly int timeoutSec;
readonly string localRoot;
enum Phase
{
Idle,
Checking,
Ready,
Downloading,
Done
}
Phase phase;
UnityWebRequest req;
CdnManifest manifest;
readonly List<CdnFile> todo = new List<CdnFile>();
int index;
long doneBefore;
public CdnDownloader(string baseUrl, string manifestName, float timeoutSec, string localRoot = null)
{
this.baseUrl = (baseUrl ?? "").Trim().TrimEnd('/');
this.manifestName = string.IsNullOrEmpty(manifestName) ? "cdn_manifest.json" : manifestName.Trim();
this.timeoutSec = Mathf.Max(1, Mathf.RoundToInt(timeoutSec > 0f ? timeoutSec : 10f));
this.localRoot = string.IsNullOrEmpty(localRoot) ? Path.Combine(Application.persistentDataPath, "cdn") : localRoot;
}
/// <summary>CDN 주소가 정해졌는가(비면 = CDN 없음).</summary>
public bool Configured
{
get { return baseUrl.Length > 0; }
}
/// <summary>CDN 에 목록 파일이 있었는가(확인 뒤).</summary>
public bool ManifestFound { get; private set; }
public string LocalRoot
{
get { return localRoot; }
}
public bool Checked
{
get { return phase != Phase.Idle && phase != Phase.Checking; }
}
public bool Needed
{
get { return Checked && todo.Count > 0; }
}
public long TotalBytes { get; private set; }
public long DoneBytes { get; private set; }
public bool Finished
{
get { return phase == Phase.Done; }
}
public string Error { get; private set; }
public void Begin()
{
Dispose();
Error = null;
todo.Clear();
index = 0;
doneBefore = 0L;
TotalBytes = 0L;
DoneBytes = 0L;
ManifestFound = false;
if (!Configured)
{
phase = Phase.Done; // CDN 없음 = 받을 것 없음
return;
}
string url = baseUrl + "/" + manifestName;
if (IsFile(url) && !File.Exists(FilePath(url)))
{
phase = Phase.Done; // 목록 파일 없음 = CDN 파일 없음
return;
}
req = UnityWebRequest.Get(url);
req.timeout = timeoutSec;
req.SendWebRequest();
phase = Phase.Checking;
}
public void Tick(float dt)
{
if (phase == Phase.Checking) TickCheck();
else if (phase == Phase.Ready || phase == Phase.Downloading) TickDownload();
}
void TickCheck()
{
if (req == null || !req.isDone) return;
bool ok = req.result == UnityWebRequest.Result.Success;
long code = req.responseCode;
string text = ok ? req.downloadHandler.text : null;
string err = req.error;
Dispose();
if (!ok)
{
if (code != 404) Debug.LogWarning("[TKS] CDN 확인 실패 → 로컬 리소스로 진행: " + err);
phase = Phase.Done;
return;
}
try
{
manifest = JsonUtility.FromJson<CdnManifest>(text);
}
catch (Exception e)
{
Debug.LogWarning("[TKS] CDN 목록 해석 실패 → 로컬 리소스로 진행: " + e.Message);
manifest = null;
}
ManifestFound = manifest != null;
if (manifest != null && manifest.files != null)
{
foreach (var f in manifest.files)
{
if (f == null || string.IsNullOrEmpty(f.path) || f.path.Contains("..")) continue;
var lp = LocalPath(f.path);
if (File.Exists(lp) && new FileInfo(lp).Length == f.size) continue;
todo.Add(f);
TotalBytes += Math.Max(0L, f.size);
}
}
phase = todo.Count > 0 ? Phase.Ready : Phase.Done;
}
void TickDownload()
{
if (req == null)
{
if (index >= todo.Count)
{
phase = Phase.Done;
DoneBytes = TotalBytes;
return;
}
var f = todo[index];
var lp = LocalPath(f.path);
Directory.CreateDirectory(Path.GetDirectoryName(lp));
req = new UnityWebRequest(baseUrl + "/" + f.path.Replace('\\', '/'), UnityWebRequest.kHttpVerbGET);
req.downloadHandler = new DownloadHandlerFile(lp + ".part") { removeFileOnAbort = true };
req.timeout = Mathf.Max(timeoutSec, 60);
req.SendWebRequest();
phase = Phase.Downloading;
return;
}
DoneBytes = doneBefore + (long)req.downloadedBytes;
if (!req.isDone) return;
bool ok = req.result == UnityWebRequest.Result.Success;
string err = req.error;
var cur = todo[index];
Dispose();
var path = LocalPath(cur.path);
if (!ok)
{
Error = cur.path + " · " + err; // BootFlow 가 retry 초 뒤 Begin() → 다시 확인(받은 것은 건너뜀)
phase = Phase.Ready;
return;
}
if (File.Exists(path)) File.Delete(path);
File.Move(path + ".part", path);
doneBefore += Math.Max(0L, cur.size);
DoneBytes = doneBefore;
index++;
}
string LocalPath(string rel)
{
return Path.Combine(localRoot, rel.Replace('/', Path.DirectorySeparatorChar));
}
static bool IsFile(string url)
{
return url.StartsWith("file://", StringComparison.OrdinalIgnoreCase);
}
static string FilePath(string url)
{
return new Uri(url).LocalPath;
}
void Dispose()
{
if (req != null)
{
req.Dispose();
req = null;
}
}
}
}