Files
bd2/plugins/LocalIdentity/SoundBankCache.cs
T

81 lines
2.8 KiB
C#

using System.Globalization;
using System.IO;
using Bd2.Client;
using BepInEx.Logging;
using UnityEngine;
namespace Bd2LocalIdentity;
internal static class SoundBankCache
{
internal static void Initialize(string bundleVersion, ManualLogSource log)
{
string instanceRoot = ClientSettings.CurrentInstance?.Root;
string persistent = string.IsNullOrEmpty(instanceRoot)
? Application.persistentDataPath
: Path.Combine(instanceRoot, "unity", "persistent");
string soundData = Path.GetFullPath(Path.Combine(persistent, "SoundData"));
string patched = Path.Combine(soundData, "Patched");
string marker = Path.Combine(soundData, "bank-cache.version");
string version = string.Join("\n", Application.version, bundleVersion,
PlayerPrefs.GetInt("SoundQuality", 1).ToString(CultureInfo.InvariantCulture));
ValidateAncestors(soundData);
if (File.Exists(marker))
{
RejectReparsePoint(marker);
if (File.ReadAllText(marker) == version) return;
}
bool cleared = Directory.Exists(patched);
if (cleared)
{
ValidateTree(patched);
DeleteTree(patched);
}
Directory.CreateDirectory(soundData);
File.WriteAllText(marker, version);
if (cleared) log.LogInfo("Cleared extracted sound banks for resource version " + bundleVersion);
}
private static void ValidateAncestors(string path)
{
for (DirectoryInfo directory = new(path); directory != null; directory = directory.Parent)
{
if (directory.Exists) RejectReparsePoint(directory.FullName);
}
}
private static void ValidateTree(string path)
{
RejectReparsePoint(path);
foreach (string entry in Directory.EnumerateFileSystemEntries(path))
{
FileAttributes attributes = RejectReparsePoint(entry);
if ((attributes & FileAttributes.Directory) != 0) ValidateTree(entry);
}
}
private static void DeleteTree(string path)
{
RejectReparsePoint(path);
foreach (string entry in Directory.EnumerateFileSystemEntries(path))
{
FileAttributes attributes = RejectReparsePoint(entry);
if ((attributes & FileAttributes.Directory) != 0)
DeleteTree(entry);
else
File.Delete(entry);
}
Directory.Delete(path);
}
private static FileAttributes RejectReparsePoint(string path)
{
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReparsePoint) != 0)
throw new InvalidDataException("Sound bank cache must not contain symbolic links or junctions: " + path);
return attributes;
}
}