otclient-redemption/src/framework/core/resourcemanager.cpp

478 lines
15 KiB
C++
Raw Normal View History

2012-04-28 22:07:47 -03:00
/*
2022-05-18 21:05:59 -03:00
* Copyright (c) 2010-2022 OTClient <https://github.com/edubart/otclient>
2012-04-28 22:07:47 -03:00
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <filesystem>
#include <ranges>
2012-04-28 22:07:47 -03:00
#include "resourcemanager.h"
#include "filestream.h"
#include <framework/core/application.h>
#include <framework/luaengine/luainterface.h>
2013-02-22 19:29:58 -03:00
#include <framework/platform/platform.h>
2012-04-28 22:07:47 -03:00
#include <physfs.h>
ResourceManager g_resources;
2020-07-02 13:00:13 -03:00
void ResourceManager::init(const char* argv0)
2012-04-28 22:07:47 -03:00
{
PHYSFS_init(argv0);
2012-10-24 18:03:15 -02:00
PHYSFS_permitSymbolicLinks(1);
2012-04-28 22:07:47 -03:00
}
void ResourceManager::terminate()
{
PHYSFS_deinit();
}
bool ResourceManager::discoverWorkDir(const std::string& existentFile)
{
// search for modules directory
2013-02-24 17:26:19 -03:00
std::string possiblePaths[] = { g_platform.getCurrentDir(),
g_resources.getBaseDir(),
2013-01-23 13:05:18 -02:00
g_resources.getBaseDir() + "../",
2013-01-23 13:43:39 -02:00
g_resources.getBaseDir() + "../share/" + g_app.getCompactName() + "/" };
2013-02-24 17:26:19 -03:00
bool found = false;
2022-04-04 20:57:52 -03:00
for (const std::string& dir : possiblePaths) {
if (!PHYSFS_mount(dir.c_str(), nullptr, 0))
2012-10-24 18:03:15 -02:00
continue;
if (PHYSFS_exists(existentFile.c_str())) {
2013-02-05 20:00:28 -02:00
g_logger.debug(stdext::format("Found work dir at '%s'", dir));
m_workDir = dir;
found = true;
break;
}
PHYSFS_unmount(dir.c_str());
}
return found;
}
bool ResourceManager::setupUserWriteDir(const std::string& appWriteDirName)
2012-04-28 22:07:47 -03:00
{
const std::string userDir = getUserDir();
std::string dirName;
#ifndef WIN32
dirName = stdext::format(".%s", appWriteDirName);
#else
dirName = appWriteDirName;
#endif
const std::string writeDir = userDir + dirName;
if (!PHYSFS_setWriteDir(writeDir.c_str())) {
if (!PHYSFS_setWriteDir(userDir.c_str()) || !PHYSFS_mkdir(dirName.c_str())) {
2019-10-10 03:14:48 +02:00
g_logger.error(stdext::format("Unable to create write directory '%s': %s", writeDir, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
2012-10-24 18:03:15 -02:00
return false;
}
}
return setWriteDir(writeDir);
}
bool ResourceManager::setWriteDir(const std::string& writeDir, bool)
{
if (!PHYSFS_setWriteDir(writeDir.c_str())) {
2019-10-10 03:14:48 +02:00
g_logger.error(stdext::format("Unable to set write directory '%s': %s", writeDir, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
return false;
2012-04-28 22:07:47 -03:00
}
2022-04-04 20:57:52 -03:00
if (!m_writeDir.empty())
removeSearchPath(m_writeDir);
m_writeDir = writeDir;
2022-04-04 20:57:52 -03:00
if (!addSearchPath(writeDir))
2012-07-17 21:31:55 +02:00
g_logger.error(stdext::format("Unable to add write '%s' directory to search path", writeDir));
2012-04-28 22:07:47 -03:00
return true;
}
bool ResourceManager::addSearchPath(const std::string& path, bool pushFront)
2012-04-28 22:07:47 -03:00
{
std::string savePath = path;
if (!PHYSFS_mount(path.c_str(), nullptr, pushFront ? 0 : 1)) {
2012-08-23 04:17:19 -03:00
bool found = false;
2022-04-04 20:57:52 -03:00
for (const std::string& searchPath : m_searchPaths) {
std::string newPath = searchPath + path;
if (PHYSFS_mount(newPath.c_str(), nullptr, pushFront ? 0 : 1)) {
2012-08-23 04:17:19 -03:00
savePath = newPath;
found = true;
break;
}
}
2022-04-04 20:57:52 -03:00
if (!found) {
2019-10-10 03:14:48 +02:00
//g_logger.error(stdext::format("Could not add '%s' to directory search path. Reason %s", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
2012-08-23 04:17:19 -03:00
return false;
}
}
2022-04-04 20:57:52 -03:00
if (pushFront)
2012-08-23 04:17:19 -03:00
m_searchPaths.push_front(savePath);
else
2012-08-23 04:17:19 -03:00
m_searchPaths.push_back(savePath);
2012-04-28 22:07:47 -03:00
return true;
}
bool ResourceManager::removeSearchPath(const std::string& path)
2012-06-19 05:46:49 -03:00
{
if (!PHYSFS_unmount(path.c_str()))
2012-06-19 05:46:49 -03:00
return false;
2021-12-03 13:59:39 -03:00
const auto it = std::find(m_searchPaths.begin(), m_searchPaths.end(), path);
assert(it != m_searchPaths.end());
m_searchPaths.erase(it);
2012-06-19 05:46:49 -03:00
return true;
}
void ResourceManager::searchAndAddPackages(const std::string& packagesDir, const std::string& packageExt)
2012-04-28 22:07:47 -03:00
{
auto files = listDirectoryFiles(packagesDir);
for (const auto& file : files | std::views::reverse) {
2022-04-04 20:57:52 -03:00
if (!file.ends_with(packageExt))
continue;
std::string package = getRealDir(packagesDir) + "/" + file;
2022-04-04 20:57:52 -03:00
if (!addSearchPath(package, true))
2019-10-10 03:14:48 +02:00
g_logger.error(stdext::format("Unable to read package '%s': %s", package, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
2012-04-28 22:07:47 -03:00
}
}
bool ResourceManager::fileExists(const std::string& fileName)
2012-04-28 22:07:47 -03:00
{
return (PHYSFS_exists(resolvePath(fileName).c_str()) && !directoryExists(fileName));
2012-04-28 22:07:47 -03:00
}
bool ResourceManager::directoryExists(const std::string& directoryName)
2012-04-28 22:07:47 -03:00
{
PHYSFS_Stat stat = {};
if (!PHYSFS_stat(resolvePath(directoryName).c_str(), &stat)) {
return false;
}
return stat.filetype == PHYSFS_FILETYPE_DIRECTORY;
2012-04-28 22:07:47 -03:00
}
void ResourceManager::readFileStream(const std::string& fileName, std::iostream& out)
2012-04-28 22:07:47 -03:00
{
const std::string buffer = readFileContents(fileName);
2022-04-04 20:57:52 -03:00
if (buffer.length() == 0) {
out.clear(std::ios::eofbit);
return;
2012-04-28 22:07:47 -03:00
}
out.clear(std::ios::goodbit);
out.write(&buffer[0], buffer.length());
out.seekg(0, std::ios::beg);
2012-04-28 22:07:47 -03:00
}
std::string ResourceManager::readFileContents(const std::string& fileName)
2012-04-28 22:07:47 -03:00
{
const std::string fullPath = resolvePath(fileName);
PHYSFS_File* file = PHYSFS_openRead(fullPath.c_str());
2022-04-04 20:57:52 -03:00
if (!file)
2019-10-10 03:14:48 +02:00
stdext::throw_exception(stdext::format("unable to open file '%s': %s", fullPath, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
2021-12-03 13:59:39 -03:00
const int fileSize = PHYSFS_fileLength(file);
std::string buffer(fileSize, 0);
PHYSFS_readBytes(file, &buffer[0], fileSize);
PHYSFS_close(file);
#if ENABLE_ENCRYPTION == 1
buffer = decrypt(buffer);
#endif
return buffer;
2012-04-28 22:07:47 -03:00
}
bool ResourceManager::writeFileBuffer(const std::string& fileName, const uchar* data, uint size)
2012-04-28 22:07:47 -03:00
{
PHYSFS_file* file = PHYSFS_openWrite(fileName.c_str());
2022-04-04 20:57:52 -03:00
if (!file) {
2019-10-10 03:14:48 +02:00
g_logger.error(PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
2012-04-28 22:07:47 -03:00
return false;
}
PHYSFS_writeBytes(file, data, size);
2012-04-28 22:07:47 -03:00
PHYSFS_close(file);
return true;
}
bool ResourceManager::writeFileStream(const std::string& fileName, std::iostream& in)
2012-04-28 22:07:47 -03:00
{
2021-12-03 13:59:39 -03:00
const std::streampos oldPos = in.tellg();
2012-04-28 22:07:47 -03:00
in.seekg(0, std::ios::end);
2021-12-03 13:59:39 -03:00
const std::streampos size = in.tellg();
2012-04-28 22:07:47 -03:00
in.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
in.read(&buffer[0], size);
2021-12-03 13:59:39 -03:00
const bool ret = writeFileBuffer(fileName, (const uchar*)&buffer[0], size);
2012-04-28 22:07:47 -03:00
in.seekg(oldPos, std::ios::beg);
return ret;
}
bool ResourceManager::writeFileContents(const std::string& fileName, const std::string& data)
2012-04-28 22:07:47 -03:00
{
#if ENABLE_ENCRYPTION == 1
return writeFileBuffer(fileName, (const uchar*)encrypt(data, std::string(ENCRYPTION_PASSWORD)).c_str(), data.size());
#else
return writeFileBuffer(fileName, (const uchar*)data.c_str(), data.size());
#endif
2012-04-28 22:07:47 -03:00
}
FileStreamPtr ResourceManager::openFile(const std::string& fileName)
2012-04-28 22:07:47 -03:00
{
const std::string fullPath = resolvePath(fileName);
PHYSFS_File* file = PHYSFS_openRead(fullPath.c_str());
2022-04-04 20:57:52 -03:00
if (!file)
2019-10-10 03:14:48 +02:00
stdext::throw_exception(stdext::format("unable to open file '%s': %s", fullPath, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
2021-12-03 13:59:39 -03:00
return { new FileStream(fullPath, file, false) };
2012-04-28 22:07:47 -03:00
}
FileStreamPtr ResourceManager::appendFile(const std::string& fileName)
2012-04-28 22:07:47 -03:00
{
PHYSFS_File* file = PHYSFS_openAppend(fileName.c_str());
2022-04-04 20:57:52 -03:00
if (!file)
2019-10-10 03:14:48 +02:00
stdext::throw_exception(stdext::format("failed to append file '%s': %s", fileName, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
2021-12-03 13:59:39 -03:00
return { new FileStream(fileName, file, true) };
2012-04-28 22:07:47 -03:00
}
FileStreamPtr ResourceManager::createFile(const std::string& fileName)
2012-04-28 22:07:47 -03:00
{
PHYSFS_File* file = PHYSFS_openWrite(fileName.c_str());
2022-04-04 20:57:52 -03:00
if (!file)
2019-10-10 03:14:48 +02:00
stdext::throw_exception(stdext::format("failed to create file '%s': %s", fileName, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
2021-12-03 13:59:39 -03:00
return { new FileStream(fileName, file, true) };
2012-04-28 22:07:47 -03:00
}
bool ResourceManager::deleteFile(const std::string& fileName)
2012-04-28 22:07:47 -03:00
{
return PHYSFS_delete(resolvePath(fileName).c_str()) != 0;
2012-04-28 22:07:47 -03:00
}
bool ResourceManager::makeDir(const std::string& directory)
2012-04-28 22:07:47 -03:00
{
return PHYSFS_mkdir(directory.c_str());
2012-04-28 22:07:47 -03:00
}
std::list<std::string> ResourceManager::listDirectoryFiles(const std::string& directoryPath)
2012-04-28 22:07:47 -03:00
{
std::list<std::string> files;
auto* const rc = PHYSFS_enumerateFiles(resolvePath(directoryPath).c_str());
2012-04-28 22:07:47 -03:00
2022-05-26 21:04:26 -03:00
for (int i = 0; rc[i] != nullptr; ++i)
files.emplace_back(rc[i]);
2012-04-28 22:07:47 -03:00
PHYSFS_freeList(rc);
return files;
}
std::vector<std::string> ResourceManager::getDirectoryFiles(const std::string& path, bool filenameOnly, bool recursive)
{
2022-04-04 20:57:52 -03:00
if (!std::filesystem::exists(path))
2021-12-03 13:59:39 -03:00
return {};
2021-12-03 13:59:39 -03:00
const std::filesystem::path p(path);
return discoverPath(p, filenameOnly, recursive);
}
std::vector<std::string> ResourceManager::discoverPath(const std::filesystem::path& path, bool filenameOnly, bool recursive)
{
std::vector<std::string> files;
/* Before doing anything, we have to add this directory to search path,
* this is needed so it works correctly when one wants to open a file. */
addSearchPath(path.generic_string(), true);
2022-04-04 20:57:52 -03:00
for (std::filesystem::directory_iterator it(path), end; it != end; ++it) {
if (std::filesystem::is_directory(it->path().generic_string()) && recursive) {
std::vector<std::string> subfiles = discoverPath(it->path(), filenameOnly, recursive);
files.insert(files.end(), subfiles.begin(), subfiles.end());
2021-07-19 19:21:06 -03:00
} else {
2022-04-04 20:57:52 -03:00
if (filenameOnly)
files.push_back(it->path().filename().string());
else
files.push_back(it->path().generic_string() + "/" + it->path().filename().string());
}
}
return files;
}
std::string ResourceManager::resolvePath(const std::string& path)
2012-04-28 22:07:47 -03:00
{
std::string fullPath;
2022-04-04 20:57:52 -03:00
if (path.starts_with("/"))
2012-04-28 22:07:47 -03:00
fullPath = path;
else {
const std::string scriptPath = "/" + g_lua.getCurrentSourcePath();
2022-04-04 20:57:52 -03:00
if (!scriptPath.empty())
2012-04-28 22:07:47 -03:00
fullPath += scriptPath + "/";
fullPath += path;
}
2022-04-04 20:57:52 -03:00
if (!(fullPath.starts_with("/")))
2012-06-01 17:39:23 -03:00
g_logger.traceWarning(stdext::format("the following file path is not fully resolved: %s", path));
stdext::replace_all(fullPath, "//", "/");
2012-04-28 22:07:47 -03:00
return fullPath;
}
std::string ResourceManager::getRealDir(const std::string& path)
{
std::string dir;
const char* cdir = PHYSFS_getRealDir(resolvePath(path).c_str());
2022-04-04 20:57:52 -03:00
if (cdir)
dir = cdir;
return dir;
}
std::string ResourceManager::getRealPath(const std::string& path)
2013-03-01 05:46:55 -03:00
{
return getRealDir(path) + "/" + path;
2013-03-01 05:46:55 -03:00
}
2012-04-28 22:07:47 -03:00
std::string ResourceManager::getBaseDir()
{
return PHYSFS_getBaseDir();
2012-04-28 22:07:47 -03:00
}
std::string ResourceManager::getUserDir()
{
2021-04-05 23:14:29 -03:00
return PHYSFS_getPrefDir("otclient", "otclient");
}
std::string ResourceManager::guessFilePath(const std::string& filename, const std::string& type)
2013-01-08 18:01:47 -02:00
{
2022-04-04 20:57:52 -03:00
if (isFileType(filename, type))
return filename;
return filename + "." + type;
}
2013-01-27 23:23:53 -02:00
bool ResourceManager::isFileType(const std::string& filename, const std::string& type)
2013-01-27 23:23:53 -02:00
{
if (filename.ends_with(std::string(".") + type))
2013-01-27 23:23:53 -02:00
return true;
return false;
}
2013-03-01 05:46:55 -03:00
ticks_t ResourceManager::getFileTime(const std::string& filename)
2013-03-01 05:46:55 -03:00
{
return g_platform.getFileModificationTime(getRealPath(filename));
}
std::string ResourceManager::encrypt(const std::string& data, const std::string& password)
{
const int len = data.length(),
plen = password.length();
std::ostringstream ss;
int j = 0;
2022-04-04 20:57:52 -03:00
for (int i = -1; ++i < len;) {
int ct = data[i];
2022-04-04 20:57:52 -03:00
if (i % 2) {
ct = ct - password[j] + i;
} else {
ct = ct + password[j] - i;
}
2021-12-03 13:59:39 -03:00
ss << static_cast<char>(ct);
2022-05-26 21:04:26 -03:00
++j;
2022-04-04 20:57:52 -03:00
if (j >= plen)
j = 0;
}
return ss.str();
}
std::string ResourceManager::decrypt(const std::string& data)
{
const auto& password = std::string(ENCRYPTION_PASSWORD);
const int len = data.length(),
plen = password.length();
std::ostringstream ss;
int j = 0;
2022-04-04 20:57:52 -03:00
for (int i = -1; ++i < len;) {
int ct = data[i];
2022-04-04 20:57:52 -03:00
if (i % 2) {
ct = ct + password[j] - i;
} else {
ct = ct - password[j] + i;
}
2021-12-03 13:59:39 -03:00
ss << static_cast<char>(ct);
++j;
2022-04-04 20:57:52 -03:00
if (j >= plen)
j = 0;
}
return ss.str();
}
uint8_t* ResourceManager::decrypt(uint8_t* data, int32_t size)
{
const auto& password = std::string(ENCRYPTION_PASSWORD);
const int plen = password.length();
2022-04-07 10:27:01 -03:00
auto* const new_Data = new uint8_t[size];
int j = 0;
2022-04-04 20:57:52 -03:00
for (int i = -1; ++i < size;) {
2021-12-03 13:59:39 -03:00
const int ct = data[i];
2022-04-04 20:57:52 -03:00
if (i % 2) {
new_Data[i] = ct + password[j] - i;
} else {
new_Data[i] = ct - password[j] + i;
}
data[i] = new_Data[i];
++j;
2022-04-04 20:57:52 -03:00
if (j >= plen)
j = 0;
}
return nullptr;
}
void ResourceManager::runEncryption(const std::string& password)
{
std::vector<std::string> excludedExtensions = { ".rar",".ogg",".xml",".dll",".exe", ".log",".otb" };
2022-04-04 20:57:52 -03:00
for (const auto& entry : std::filesystem::recursive_directory_iterator("./")) {
std::string ext = entry.path().extension().string();
2022-04-04 20:57:52 -03:00
if (std::find(excludedExtensions.begin(), excludedExtensions.end(), ext) != excludedExtensions.end())
continue;
std::ifstream ifs(entry.path().string(), std::ios_base::binary);
2022-04-07 10:27:01 -03:00
std::string data((std::istreambuf_iterator(ifs)), std::istreambuf_iterator<char>());
ifs.close();
data = encrypt(data, password);
save_string_into_file(data, entry.path().string());
}
}
void ResourceManager::save_string_into_file(const std::string& contents, const std::string& name)
{
std::ofstream datFile;
datFile.open(name, std::ofstream::binary | std::ofstream::trunc | std::ofstream::out);
datFile.write(contents.c_str(), contents.size());
datFile.close();
}