using System; using System.Collections.Generic; using System.IO; // 曲包來源:package 資料夾(像插上的隨身碟一樣,裡面有什麼就玩什麼) // package/*.zip 曲包 zip:解壓到快取資料夾再讀取,zip 本身不動 // package/<資料夾>/ 已解開的曲包(資料夾內直接有 config.json),直接讀取 // 快取以「檔名 + 大小 + 修改時間」區分,zip 被換掉或刪掉時快取跟著更新 / 清除 // 不使用 UnityEngine,可在背景執行緒與 EditMode 測試中使用 public static class PackLibrary { public class ScanResult { public readonly List songs = new List(); public readonly List errors = new List(); // 這次新發現的錯誤(同一個檔案只回報一次) public readonly List added = new List(); // 和上次相比新出現的曲包 public bool changed; // 曲包清單有變 public bool pending; // 有檔案還在寫入,晚點再掃 } // 剛修改過的 zip 可能還在複製中(USB、瀏覽器下載),先跳過 public static TimeSpan SettleTime = TimeSpan.FromSeconds(2); private static readonly HashSet reported = new HashSet(); private static string lastSignature = ""; private static HashSet lastSources = null; public static ScanResult Scan(string packageDir, string cacheDir) { var r = new ScanResult(); Directory.CreateDirectory(packageDir); Directory.CreateDirectory(cacheDir); var found = new List(); var usedCache = new HashSet(StringComparer.OrdinalIgnoreCase); var nowReported = new HashSet(); foreach (var zip in Directory.GetFiles(packageDir, "*.zip")) { var fi = new FileInfo(zip); if (DateTime.UtcNow - fi.LastWriteTimeUtc < SettleTime) { r.pending = true; continue; } string key = CacheKey(fi); string dir = Path.Combine(cacheDir, key); usedCache.Add(key); try { SongInfo s = File.Exists(Path.Combine(dir, SongInfo.ConfigName)) ? SongInfo.FromDir(dir) : PackReader.Extract(zip, dir); s.source = zip; found.Add(s); } catch (Exception e) { Report(r, nowReported, key, $"{fi.Name}:{PackReader.Describe(e)}"); } } foreach (var dir in Directory.GetDirectories(packageDir)) { if (!File.Exists(Path.Combine(dir, SongInfo.ConfigName))) continue; string name = Path.GetFileName(dir); try { var s = SongInfo.FromDir(dir); if (s.MusicPath == null) throw new PackReader.PackException("缺少音樂"); if (s.FirstLevel() == 0) throw new PackReader.PackException("沒有任何難度的譜面"); s.source = dir; found.Add(s); } catch (Exception e) { Report(r, nowReported, "dir:" + dir + Directory.GetLastWriteTimeUtc(dir).Ticks, $"{name}:{PackReader.Describe(e)}"); } } // 同一個 id 只留最新的來源 found.Sort((a, b) => LastWrite(b.source).CompareTo(LastWrite(a.source))); var ids = new Dictionary(); foreach (var s in found) { if (ids.TryGetValue(s.id, out var kept)) { Report(r, nowReported, "dup:" + s.source, $"{Path.GetFileName(s.source)} 和 {Path.GetFileName(kept.source)} 的 id 相同({s.id}),只使用較新的"); continue; } ids[s.id] = s; r.songs.Add(s); } r.songs.Sort((a, b) => string.Compare(a.name, b.name, StringComparison.OrdinalIgnoreCase)); // 只保留仍有錯誤的紀錄:檔案修好或刪掉後再壞掉會再回報一次 reported.IntersectWith(nowReported); // 清掉沒用到的快取 foreach (var dir in Directory.GetDirectories(cacheDir)) { string name = Path.GetFileName(dir); if (name.EndsWith(".tmp") || !usedCache.Contains(name)) { try { Directory.Delete(dir, true); } catch { } } } var sources = new HashSet(); var sig = new System.Text.StringBuilder(); foreach (var s in r.songs) { sources.Add(s.source); sig.Append(s.source).Append('|').Append(s.dir).Append('\n'); } r.changed = sig.ToString() != lastSignature; if (lastSources != null) foreach (var s in r.songs) if (!lastSources.Contains(s.source)) r.added.Add(s); lastSignature = sig.ToString(); lastSources = sources; return r; } // 重設「上次掃描」的紀錄(換了 package 資料夾、測試用) public static void ResetState() { reported.Clear(); lastSignature = ""; lastSources = null; } private static void Report(ScanResult r, HashSet nowReported, string key, string message) { nowReported.Add(key); if (reported.Add(key)) r.errors.Add(message); } private static DateTime LastWrite(string path) => File.Exists(path) ? File.GetLastWriteTimeUtc(path) : Directory.GetLastWriteTimeUtc(path); // 快取資料夾名稱:檔名(去掉不安全字元)+ 大小與修改時間的雜湊 public static string CacheKey(FileInfo fi) { string name = Path.GetFileNameWithoutExtension(fi.Name); var safe = new System.Text.StringBuilder(); foreach (char c in name) safe.Append(char.IsLetterOrDigit(c) && c < 128 ? char.ToLowerInvariant(c) : '-'); string s = safe.ToString(); if (s.Length > 32) s = s.Substring(0, 32); ulong h = 14695981039346656037UL; // FNV-1a foreach (char c in $"{fi.Name}|{fi.Length}|{fi.LastWriteTimeUtc.Ticks}") { h ^= c; h *= 1099511628211UL; } return $"{s}-{h:x16}"; } }