// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Core.FileSystem
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DataReader.Cpk;
using UnityEngine;
///
/// File system wrapper for CPack archives
///
public class CpkFileSystem : ICpkFileSystem
{
private readonly string _rootPath;
private readonly ConcurrentDictionary _cpkArchives = new();
private readonly CrcHash _crcHash;
private CpkFileSystem() {} // Hide default constructor
public CpkFileSystem(string rootPath, CrcHash crcHash)
{
if (!rootPath.EndsWith(Path.DirectorySeparatorChar))
{
rootPath += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(rootPath))
{
var error = "Failed to initialize CpkFileSystem" +
$" since application's root directory does not exists: {rootPath}";
Debug.LogError(error);
throw new ArgumentException(error);
}
_rootPath = rootPath;
_crcHash = crcHash;
}
public string GetRootPath()
{
return _rootPath;
}
///
/// Mount a Cpk archive to the file system.
///
/// CPK file relative path
public void Mount(string cpkFileRelativePath)
{
var cpkFileName = Path.GetFileName(cpkFileRelativePath).ToLower();
if (_cpkArchives.ContainsKey(cpkFileName.ToLower()))
{
Debug.LogWarning($"{cpkFileRelativePath} already mounted.");
return;
}
Debug.Log($"CpkFileSystem mounting: {_rootPath + cpkFileRelativePath}");
var cpkArchive = new CpkArchive(_rootPath + cpkFileRelativePath, _crcHash);
cpkArchive.Init();
_cpkArchives[cpkFileName] = cpkArchive;
}
///
/// Check if file exists in the archive using virtual path.
///
/// File virtual path {Cpk file name}.cpk\{File relative path inside archive}
/// Example: music.cpk\music\PI01.mp3
/// True if file exists
public bool FileExists(string fileVirtualPath)
{
ParseFileVirtualPath(fileVirtualPath, out var cpkFileName, out var relativeVirtualPath);
return _cpkArchives.Keys.Contains(cpkFileName.ToLower()) &&
_cpkArchives[cpkFileName].FileExists(relativeVirtualPath);
}
///
/// Read all bytes of the given file.
///
/// File virtual path inside CPK archive
/// Decompressed, ready-to-go file content in byte array
public byte[] ReadAllBytes(string fileVirtualPath)
{
ParseFileVirtualPath(fileVirtualPath, out var cpkFileName, out var relativeVirtualPath);
return _cpkArchives[cpkFileName].ReadAllBytes(relativeVirtualPath);
}
///
/// Preload archive into memory for faster read performance.
///
public void LoadArchiveIntoMemory(string cpkFileName)
{
if (_cpkArchives.ContainsKey(cpkFileName.ToLower()))
{
Debug.Log($"File system caching {cpkFileName} into memory.");
_cpkArchives[cpkFileName.ToLower()].LoadArchiveIntoMemory();
}
else
{
throw new Exception($"{cpkFileName} not mounted yet.");
}
}
///
/// Dispose in-memory archive data.
///
public void DisposeInMemoryArchive(string cpkFileName)
{
if (_cpkArchives.ContainsKey(cpkFileName.ToLower()))
{
Debug.Log($"File system disposing in-memory cache: {cpkFileName}");
_cpkArchives[cpkFileName.ToLower()].DisposeInMemoryArchive();
}
else
{
throw new Exception($"{cpkFileName} not mounted yet.");
}
}
///
/// Dispose all in-memory archive data.
///
public void DisposeAllInMemoryArchives()
{
foreach (var cpkArchive in _cpkArchives.Values)
{
cpkArchive.DisposeInMemoryArchive();
}
}
///
/// Search files using keyword.
///
///
/// File path enumerable
public IEnumerable Search(string keyword = "")
{
var results = new ConcurrentBag>();
Parallel.ForEach(_cpkArchives, archive =>
{
var rootNodes = archive.Value.GetRootEntries();
results.Add(from result in SearchInternal(rootNodes, keyword)
select archive.Key + CpkConstants.CpkDirectorySeparatorChar + result);
});
var resultList = new List();
foreach (var result in results)
{
resultList.AddRange(result);
}
return resultList;
}
private void ParseFileVirtualPath(string fullVirtualPath, out string cpkFileName, out string relativeVirtualPath)
{
if (!fullVirtualPath.Contains(CpkConstants.CpkDirectorySeparatorChar))
{
throw new ArgumentException("File virtual path is invalid.");
}
cpkFileName = fullVirtualPath[..fullVirtualPath.IndexOf(CpkConstants.CpkDirectorySeparatorChar)].ToLower();
relativeVirtualPath = fullVirtualPath[(fullVirtualPath.IndexOf(CpkConstants.CpkDirectorySeparatorChar) + 1)..];
}
private IEnumerable SearchInternal(IEnumerable nodes, string keyword)
{
foreach (var node in nodes)
{
if (node.IsDirectory)
{
foreach (var result in SearchInternal(node.Children, keyword))
{
yield return result;
}
}
else if (node.VirtualPath.ToLower().Contains(keyword.ToLower()))
{
yield return node.VirtualPath;
}
}
}
}
}