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

789 lines
24 KiB
C++
Raw Normal View History

2012-04-28 22:07:47 -03:00
/*
* Copyright (c) 2010-2026 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.
*/
2024-12-13 22:43:36 -03:00
#include "resourcemanager.h"
2012-04-28 22:07:47 -03:00
#include <physfs.h>
#include "filestream.h"
#include "graphicalapplication.h"
#include "framework/graphics/drawpoolmanager.h"
#include "framework/net/protocolhttp.h"
#include "framework/platform/platform.h"
#include "framework/util/crypt.h"
2012-04-28 22:07:47 -03:00
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);
2023-05-11 11:38:24 -03:00
#if defined(WIN32)
char fileName[255];
2024-12-13 22:43:36 -03:00
GetModuleFileNameA(nullptr, fileName, sizeof(fileName));
2023-05-11 11:38:24 -03:00
m_binaryPath = std::filesystem::absolute(fileName);
#elif defined(ANDROID)
// nothing
#else
m_binaryPath = std::filesystem::absolute(argv0);
#endif
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(),
g_resources.getBaseDir() + "/game_data/",
g_resources.getBaseDir() + "../",
g_resources.getBaseDir() + "../share/" + g_app.getCompactName() + "/",
};
2013-02-24 17:26:19 -03:00
bool found = false;
2023-06-30 20:13:09 -03:00
for (const auto& 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())) {
g_logger.debug("Found work dir at '{}'", 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 = fmt::format(".{}", 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())) {
g_logger.error(
"Unable to create write directory '{}': {}",
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())) {
g_logger.error(
"Unable to set write directory '{}': {}",
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))
g_logger.error("Unable to add write '{}' directory to search path", writeDir);
2012-04-28 22:07:47 -03:00
return true;
}
2024-12-13 22:43:36 -03:00
bool ResourceManager::addSearchPath(const std::string& path, const 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;
2023-06-30 20:13:09 -03:00
for (const auto& 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) {
/*g_logger.error(
"Could not add '{}' to directory search path. Reason {}",
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;
2024-12-13 22:43:36 -03:00
const auto it = std::ranges::find(m_searchPaths, 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);
2024-12-13 22:43:36 -03:00
for (auto& file : std::ranges::reverse_view(files)) {
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))
g_logger.error(
"Unable to read package '{}': {}",
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
{
if (fileName.find("/downloads") != std::string::npos)
return g_http.getFile(fileName.substr(10)) != nullptr;
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
{
if (directoryName == "/downloads")
return true;
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);
2025-01-24 21:16:33 -03:00
if (fullPath.find(AY_OBFUSCATE("/downloads")) != std::string::npos) {
2024-12-13 22:43:36 -03:00
const auto dfile = g_http.getFile(fullPath.substr(10));
if (dfile)
return std::string(dfile->response.begin(), dfile->response.end());
}
PHYSFS_File* file = PHYSFS_openRead(fullPath.c_str());
2022-04-04 20:57:52 -03:00
if (!file)
2025-06-11 18:57:23 -04:00
throw Exception("unable to open file '{}': {}", 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);
2024-12-24 23:38:07 -03:00
#if ENABLE_ENCRYPTION == 1
const std::string encHeader(ENCRYPTION_HEADER);
if (buffer.size() >= encHeader.size() &&
buffer.compare(0, encHeader.size(), encHeader) == 0) {
buffer = buffer.substr(encHeader.size());
2024-09-14 18:33:15 -03:00
buffer = decrypt(buffer);
}
#endif
return buffer;
2012-04-28 22:07:47 -03:00
}
2024-12-13 22:43:36 -03:00
bool ResourceManager::writeFileBuffer(const std::string& fileName, const uint8_t* data, const uint32_t size, const bool createDirectory)
2012-04-28 22:07:47 -03:00
{
2023-05-11 11:38:24 -03:00
if (createDirectory) {
const auto& path = std::filesystem::path(fileName);
const auto& dirPath = path.parent_path().string();
PHYSFS_Stat stat = {};
const bool dirExists = PHYSFS_stat(dirPath.c_str(), &stat) && stat.filetype == PHYSFS_FILETYPE_DIRECTORY;
if (!dirExists) {
2023-05-11 11:38:24 -03:00
if (!PHYSFS_mkdir(dirPath.c_str())) {
g_logger.error(
"Unable to create write directory '{}': {}",
dirPath,
PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())
);
2023-05-11 11:38:24 -03:00
return false;
}
}
}
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);
const bool ret = writeFileBuffer(fileName, (const uint8_t*)&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
{
return writeFileBuffer(fileName, (const uint8_t*)data.c_str(), data.size());
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)
2025-06-11 18:57:23 -04:00
throw Exception("unable to open file '{}': {}", fullPath, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
return { std::make_shared<FileStream>(fullPath, file, false) };
2012-04-28 22:07:47 -03:00
}
2023-01-24 22:09:04 -03:00
FileStreamPtr ResourceManager::appendFile(const std::string& fileName) const
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)
2025-06-11 18:57:23 -04:00
throw Exception("failed to append file '{}': {}", fileName, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
return { std::make_shared<FileStream>(fileName, file, true) };
2012-04-28 22:07:47 -03:00
}
2023-01-24 22:09:04 -03:00
FileStreamPtr ResourceManager::createFile(const std::string& fileName) const
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)
2025-06-11 18:57:23 -04:00
throw Exception("failed to create file '{}': {}", fileName, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
return { std::make_shared<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
}
2024-12-13 22:43:36 -03:00
std::list<std::string> ResourceManager::listDirectoryFiles(const std::string& directoryPath, const bool fullPath /* = false */, const bool raw /*= false*/, const bool recursive)
2012-04-28 22:07:47 -03:00
{
std::list<std::string> files;
2022-11-17 15:35:27 -03:00
const auto path = raw ? directoryPath : resolvePath(directoryPath);
const auto rc = PHYSFS_enumerateFiles(path.c_str());
if (!rc)
return files;
for (int i = 0; rc[i] != nullptr; i++) {
std::string fileOrDir = rc[i];
2023-05-11 11:38:24 -03:00
if (fullPath) {
if (path != "/")
fileOrDir = path + "/" + fileOrDir;
else
fileOrDir = path + fileOrDir;
}
2022-11-17 15:35:27 -03:00
if (recursive && directoryExists("/" + fileOrDir)) {
2022-12-27 19:40:33 -03:00
const auto& moreFiles = listDirectoryFiles(fileOrDir, fullPath, raw, recursive);
2022-11-17 15:35:27 -03:00
files.insert(files.end(), moreFiles.begin(), moreFiles.end());
} else {
files.push_back(fileOrDir);
}
}
2012-04-28 22:07:47 -03:00
PHYSFS_freeList(rc);
2022-11-17 15:35:27 -03:00
files.sort();
2012-04-28 22:07:47 -03:00
return files;
}
2024-12-13 22:43:36 -03:00
std::vector<std::string> ResourceManager::getDirectoryFiles(const std::string& path, const bool filenameOnly, const 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);
}
2024-12-13 22:43:36 -03:00
std::vector<std::string> ResourceManager::discoverPath(const std::filesystem::path& path, const bool filenameOnly, const 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 if (g_drawPool.isPreDrawing())
fullPath = "/" + path;
2012-04-28 22:07:47 -03:00
else {
2022-08-31 18:13:07 -03:00
if (const std::string scriptPath = "/" + g_lua.getCurrentSourcePath(); !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("/")))
g_logger.traceWarning(fmt::format("the following file path is not fully resolved: {}", 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;
2022-08-31 18:13:07 -03:00
if (const char* cdir = PHYSFS_getRealDir(resolvePath(path).c_str()))
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()
{
#ifdef ANDROID
return g_androidManager.getAppBaseDir();
#else
return PHYSFS_getBaseDir();
#endif
2012-04-28 22:07:47 -03:00
}
std::string ResourceManager::getUserDir()
{
#ifdef ANDROID
return getBaseDir() + "/";
#elif defined(__EMSCRIPTEN__)
return "/user/";
#else
static const char* orgName = g_app.getOrganizationName().data();
static const char* appName = g_app.getCompactName().data();
2024-12-13 22:43:36 -03:00
return PHYSFS_getPrefDir(orgName, appName);
#endif
}
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
Framework Cleanup (no more client code in fw) (#666) * Moved <client/...> includes from framework (we should never cross contaminate fw/client) GraphicalApplication was the biggest offender, we need to ensure that this is a base graphical application class and not a client specific class. Created UIQrCode widget Minor additions and clean up * Fix for latest version * Finished, no more client code in the framework! * Update README * Revert * fix cmake build * Update review suggestions Remove `image-source-base64` in favour of `image-source: base64:/path/image` * Added CHANGELOG.md to help with noting breaking changes * More framework improvements and some client improvements: - Readd FRAMEWORK_GRAPHICS (so we can have no graphics support) - Added creatureDiagonalWalkSpeed/playerDiagonalWalkSpeed upgrade_classification - Added getCountOrSubType to Item lua binding - Added startEvent to EventDispatcher (to start stored ScheduledEvent's) - Removed g_drawPool from the application.cpp (we use dispatchPoll) - Added startTime calculator when logging module starts - Allow commenting out otml using # - Added some math functions - Added onAdopted/onAbandoned to UIWidget for when they are added to/from parent UIWidget's - Added some more helper methods to UIWidget - Added visibleOnly to UIWidget getChildBefore/getChildAfter methods - Added onHovered for only hovered widget events - Make getChildIndex take child as optional parameter, if not provided it returns this widgets child index - Added sha1Encrpyt method - General clean up * Rename ApplicationDrawEvents#setLoadingAsyncTexture to onLoadingAsyncTextureChanged * Update setup.otml * Added a todo * Clean up * Revert old code (oops) * Reverting onAdopted, etc * Add improved version * Improve getHoveredChild * Recommended fixes/clean up * Moved missed graphical sources to FRAMEWORK_GRAPHICS
2023-12-07 19:28:42 -05:00
std::string ResourceManager::getFileName(const std::string& filePath)
{
return std::filesystem::path(filePath).filename().string();
}
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();
}
2024-12-13 22:43:36 -03:00
uint8_t* ResourceManager::decrypt(uint8_t* data, const int32_t size)
{
const auto& password = std::string(ENCRYPTION_PASSWORD);
const int plen = password.length();
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) {
data[i] = ct + password[j] - i;
} else {
data[i] = ct - password[j] + i;
}
++j;
2022-04-04 20:57:52 -03:00
if (j >= plen)
j = 0;
}
return data;
}
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("./")) {
2022-08-31 18:13:07 -03:00
if (std::string ext = entry.path().extension().string();
2024-12-13 22:43:36 -03:00
std::ranges::find(excludedExtensions, 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);
2024-09-14 18:33:15 -03:00
std::string finalData = std::string(ENCRYPTION_HEADER) + data;
save_string_into_file(finalData, 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();
}
2023-05-11 11:38:24 -03:00
std::string ResourceManager::fileChecksum(const std::string& path) {
2023-05-11 11:38:24 -03:00
static stdext::map<std::string, std::string> cache;
2024-12-13 22:43:36 -03:00
const auto it = cache.find(path);
2023-05-11 11:38:24 -03:00
if (it != cache.end())
return it->second;
PHYSFS_File* file = PHYSFS_openRead(path.c_str());
if (!file)
return "";
2024-12-13 22:43:36 -03:00
const int fileSize = PHYSFS_fileLength(file);
2023-05-11 11:38:24 -03:00
std::string buffer(fileSize, 0);
2024-12-13 22:43:36 -03:00
PHYSFS_readBytes(file, &buffer[0], fileSize);
2023-05-11 11:38:24 -03:00
PHYSFS_close(file);
auto checksum = g_crypt.crc32(buffer, false);
cache[path] = checksum;
return checksum;
}
std::unordered_map<std::string, std::string> ResourceManager::filesChecksums()
2023-05-11 11:38:24 -03:00
{
std::unordered_map<std::string, std::string> ret;
2023-05-11 11:38:24 -03:00
auto files = listDirectoryFiles("/", true, false, true);
2024-12-13 22:43:36 -03:00
for (auto& filePath : std::ranges::reverse_view(files)) {
2023-05-11 11:38:24 -03:00
PHYSFS_File* file = PHYSFS_openRead(filePath.c_str());
if (!file)
continue;
2024-12-13 22:43:36 -03:00
const int fileSize = PHYSFS_fileLength(file);
2023-05-11 11:38:24 -03:00
std::string buffer(fileSize, 0);
2024-12-13 22:43:36 -03:00
PHYSFS_readBytes(file, &buffer[0], fileSize);
2023-05-11 11:38:24 -03:00
PHYSFS_close(file);
2024-12-13 22:43:36 -03:00
const auto checksum = g_crypt.crc32(buffer, false);
2023-05-11 11:38:24 -03:00
ret[filePath] = checksum;
}
return ret;
}
std::string ResourceManager::selfChecksum() {
2023-05-11 11:38:24 -03:00
#ifdef ANDROID
return "";
#else
static std::string checksum;
if (!checksum.empty())
return checksum;
std::ifstream file(m_binaryPath.string(), std::ios::binary);
if (!file.is_open())
return "";
std::string buffer(std::istreambuf_iterator<char>(file), {});
file.close();
checksum = g_crypt.crc32(buffer, false);
return checksum;
#endif
}
void ResourceManager::updateFiles(const std::set<std::string>& files) {
2025-06-25 17:35:28 -04:00
g_logger.info("Updating client, {} files", files.size());
2023-05-11 11:38:24 -03:00
const auto& oldWriteDir = getWriteDir();
setWriteDir(getWorkDir());
for (auto fileName : files) {
if (fileName.empty())
continue;
if (fileName.size() > 1 && fileName[0] == '/')
fileName = fileName.substr(1);
auto dFile = g_http.getFile(fileName);
if (dFile) {
if (!writeFileBuffer(fileName, (const uint8_t*)dFile->response.data(), dFile->response.size(), true)) {
g_logger.error("Cannot write file: {}", fileName);
2023-05-11 11:38:24 -03:00
} else {
//g_logger.info("Updated file: {}", fileName);
2023-05-11 11:38:24 -03:00
}
} else {
g_logger.error("Cannot find file: {} in downloads", fileName);
2023-05-11 11:38:24 -03:00
}
}
setWriteDir(oldWriteDir);
2025-06-25 17:35:28 -04:00
addSearchPath(getWorkDir(), true);
2023-05-11 11:38:24 -03:00
}
void ResourceManager::updateExecutable(std::string fileName)
{
#if defined(ANDROID) || defined(FREE_VERSION)
g_logger.fatal("Executable cannot be updated on android or in free version");
#else
if (fileName.size() <= 2) {
g_logger.fatal("Invalid executable name");
}
if (fileName[0] == '/')
fileName = fileName.substr(1);
2024-12-13 22:43:36 -03:00
const auto dFile = g_http.getFile(fileName);
2023-05-11 11:38:24 -03:00
if (!dFile)
g_logger.fatal("Cannot find executable: {} in downloads", fileName);
2023-05-11 11:38:24 -03:00
const auto& oldWriteDir = getWriteDir();
setWriteDir(getWorkDir());
2024-12-13 22:43:36 -03:00
const std::filesystem::path path(m_binaryPath);
const auto newBinary = path.stem().string() + "-" + std::to_string(time(nullptr)) + path.extension().string();
g_logger.info("Updating binary file: {}", newBinary);
2023-05-11 11:38:24 -03:00
PHYSFS_file* file = PHYSFS_openWrite(newBinary.c_str());
if (!file) {
return g_logger.fatal(
"can't open {} for writing: {}",
newBinary,
PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())
);
}
2023-05-11 11:38:24 -03:00
PHYSFS_writeBytes(file, dFile->response.data(), dFile->response.size());
PHYSFS_close(file);
setWriteDir(oldWriteDir);
#endif
}
bool ResourceManager::launchCorrect(const std::vector<std::string>& args) { // curently works only on windows
2023-05-11 11:38:24 -03:00
#if (defined(ANDROID) || defined(FREE_VERSION))
return false;
#else
const auto normalizeName = [](std::string name) {
const auto dash = name.find('-');
if (dash != std::string::npos) {
name = name.substr(0, dash);
}
stdext::tolower(name);
return name;
};
auto fileName2 = normalizeName(m_binaryPath.stem().string());
2023-05-11 11:38:24 -03:00
2024-12-13 22:43:36 -03:00
const std::filesystem::path path(m_binaryPath.parent_path());
2023-05-11 11:38:24 -03:00
std::error_code ec;
if (path.empty() || !std::filesystem::exists(path, ec) || ec) {
return false;
}
2024-12-13 22:43:36 -03:00
auto lastWrite = last_write_time(m_binaryPath, ec);
2023-05-11 11:38:24 -03:00
std::filesystem::path binary = m_binaryPath;
for (auto it = std::filesystem::directory_iterator(path, ec);
!ec && it != std::filesystem::directory_iterator();
++it) {
const auto& entry = *it;
2024-12-13 22:43:36 -03:00
if (is_directory(entry.path()))
2023-05-11 11:38:24 -03:00
continue;
auto fileName1 = normalizeName(entry.path().stem().string());
2023-05-11 11:38:24 -03:00
if (fileName1 != fileName2)
continue;
if (entry.path().extension() == m_binaryPath.extension()) {
2024-05-21 18:31:49 -03:00
std::error_code _ec;
2024-12-13 22:43:36 -03:00
auto writeTime = last_write_time(entry.path(), _ec);
2024-05-21 18:31:49 -03:00
if (!_ec && writeTime > lastWrite) {
2023-05-11 11:38:24 -03:00
lastWrite = writeTime;
binary = entry.path();
}
}
}
if (ec) {
return false;
}
for (auto it = std::filesystem::directory_iterator(path, ec);
!ec && it != std::filesystem::directory_iterator();
++it) { // remove old
const auto& entry = *it;
2024-12-13 22:43:36 -03:00
if (is_directory(entry.path()))
2023-05-11 11:38:24 -03:00
continue;
auto fileName1 = normalizeName(entry.path().stem().string());
2023-05-11 11:38:24 -03:00
if (fileName1 != fileName2)
continue;
if (entry.path().extension() == m_binaryPath.extension()) {
if (binary == entry.path())
continue;
2024-05-21 18:31:49 -03:00
std::error_code _ec;
std::filesystem::remove(entry.path(), _ec);
2023-05-11 11:38:24 -03:00
}
}
if (ec) {
return false;
}
2023-05-11 11:38:24 -03:00
if (binary == m_binaryPath)
return false;
g_platform.spawnProcess(binary.string(), args);
return true;
#endif
2023-11-21 22:27:20 -03:00
}
2024-05-21 18:31:49 -03:00
std::string ResourceManager::createArchive(const std::unordered_map<std::string, std::string>& /*files*/) { return ""; }
2023-11-21 22:27:20 -03:00
2024-05-28 00:10:25 -03:00
std::unordered_map<std::string, std::string> ResourceManager::decompressArchive(std::string /*dataOrPath*/)
2023-11-21 22:27:20 -03:00
{
std::unordered_map<std::string, std::string> ret;
2023-11-21 22:27:20 -03:00
return ret;
}