// MassBuilderSaveTool // Copyright (C) 2021-2022 Guillaume Jacquemin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #include #include #include #include #include #include #include #include #include #include #include #include #include "ProfileManager.h" using namespace Containers::Literals; ProfileManager::ProfileManager(Containers::StringView save_dir, Containers::StringView backup_dir): _saveDirectory{save_dir}, _backupsDirectory{backup_dir} { _ready = refreshProfiles(); } auto ProfileManager::ready() const -> bool { return _ready; } auto ProfileManager::lastError() -> Containers::StringView { return _lastError; } auto ProfileManager::profiles() -> Containers::ArrayView { return _profiles; } auto ProfileManager::refreshProfiles() -> bool { _profiles = Containers::Array{}; using Utility::Directory::Flag; auto files = Utility::Directory::list(_saveDirectory, Flag::SkipSpecial|Flag::SkipDirectories|Flag::SkipDotAndDotDot); auto predicate = [](Containers::StringView file)->bool{ std::regex legacy_regex("(Demo)?Profile[0-9]{17}\\.sav", std::regex::nosubs); std::regex new_regex("(Demo)?ProfilePMCSlot[0-9]{3}\\.sav", std::regex::nosubs); std::cmatch m; return !std::regex_match(file.data(), m, legacy_regex) && !std::regex_match(file.data(), m, new_regex); }; files.erase(std::remove_if(files.begin(), files.end(), predicate), files.end()); for(const auto& file : files) { Profile profile{Utility::Directory::join(_saveDirectory, file)}; if(!profile.valid()) { Utility::Warning{} << "Profile"_s << file.c_str() << "is invalid:"_s << profile.lastError(); continue; } arrayAppend(_profiles, std::move(profile)); } if(_profiles.empty()) { _lastError = "No valid profiles were found."_s; return false; } return true; } auto ProfileManager::getProfile(std::size_t index) -> Profile* { return index <= _profiles.size() ? &(_profiles[index]) : nullptr; } auto ProfileManager::deleteProfile(std::size_t index, bool delete_builds) -> bool { if(!Utility::Directory::rm(Utility::Directory::join(_saveDirectory, _profiles[index].filename()))) { _lastError = Utility::format("Couldn't delete {} (filename: {}).", _profiles[index].companyName(), _profiles[index].filename()); refreshProfiles(); return false; } if(delete_builds) { for(UnsignedByte i = 0; i < 32; ++i) { auto filename = Utility::format("{}Unit{:.2d}{}.sav", _profiles[index].type() == ProfileType::Demo ? "Demo": "", i, _profiles[index].account()); Utility::Directory::rm(Utility::Directory::join(_saveDirectory, filename)); } } auto file = _profiles[index].filename(); auto it = std::remove_if(_profiles.begin(), _profiles.end(), [&file](Profile& profile){ return profile.filename() == file; }); if(it != _profiles.end()) { arrayRemoveSuffix(_profiles, 1); } return true; } auto ProfileManager::backupProfile(std::size_t index, bool backup_builds) -> bool { std::time_t timestamp = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::tm* time = std::localtime(×tamp); auto filename = Utility::format("{}_{}{:.2d}{:.2d}_{:.2d}{:.2d}{:.2d}.mbprofbackup", Utility::String::replaceAll(_profiles[index].companyName(), " ", "_"), time->tm_year + 1900, time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec); int error_code = 0; zip_error_t error; zip_t* zip = zip_open(Utility::Directory::join(_backupsDirectory, filename).c_str(), ZIP_CREATE|ZIP_TRUNCATE, &error_code); if(zip == nullptr) { zip_error_init_with_code(&error, error_code); _lastError = zip_error_strerror(&error); return false; } zip_source_t* profile_source = zip_source_file(zip, Utility::Directory::toNativeSeparators(Utility::Directory::join(_saveDirectory, _profiles[index].filename())).c_str(), 0, 0); if(profile_source == nullptr) { _lastError = zip_strerror(zip); zip_source_free(profile_source); return false; } if(zip_file_add(zip, _profiles[index].filename().data(), profile_source, ZIP_FL_ENC_UTF_8) == -1) { _lastError = zip_strerror(zip); zip_source_free(profile_source); return false; } auto comment = "|"_s.join({_profiles[index].companyName(), _profiles[index].type() == ProfileType::Demo ? "demo"_s : "full"_s, Utility::format("{}-{:.2d}-{:.2d}-{:.2d}-{:.2d}-{:.2d}", time->tm_year + 1900, time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec)}); zip_set_archive_comment(zip, comment.data(), comment.size()); if(backup_builds) { for(UnsignedByte i = 0; i < 32; ++i) { auto build_filename = Utility::format("{}Unit{:.2d}{}.sav", _profiles[index].type() == ProfileType::Demo ? "Demo"_s : ""_s, i, _profiles[index].account()); if(!Utility::Directory::exists(Utility::Directory::join(_saveDirectory, build_filename))) { continue; } zip_source_t* build_source = zip_source_file(zip, Utility::Directory::toNativeSeparators(Utility::Directory::join(_saveDirectory, build_filename)).c_str(), 0, 0); if(build_source == nullptr) { zip_source_free(build_source); continue; } if(zip_file_add(zip, build_filename.data(), build_source, ZIP_FL_ENC_UTF_8) == -1) { zip_source_free(build_source); continue; } } } if(zip_close(zip) == -1) { _lastError = zip_strerror(zip); return false; } refreshBackups(); return true; } auto ProfileManager::backups() -> Containers::ArrayView { return _backups; } void ProfileManager::refreshBackups() { _backups = Containers::Array{}; using Utility::Directory::Flag; std::vector files = Utility::Directory::list(_backupsDirectory, Flag::SkipSpecial|Flag::SkipDirectories|Flag::SkipDotAndDotDot); auto predicate = [](Containers::StringView file)->bool{ return !file.hasSuffix(".mbprofbackup"_s); }; files.erase(std::remove_if(files.begin(), files.end(), predicate), files.end()); int error_code = 0; zip_t* zip = nullptr; for(const std::string& file : files) { Backup backup; backup.filename = file; zip = zip_open(Utility::Directory::join(_backupsDirectory, file).c_str(), ZIP_RDONLY, &error_code); if(zip == nullptr) { continue; } Containers::ScopeGuard guard{zip, zip_close}; int comment_length; Containers::StringView comment = zip_get_archive_comment(zip, &comment_length, ZIP_FL_UNCHANGED); if(comment == nullptr) { continue; } auto info = comment.split('|'); if(info.size() != 3) { continue; } backup.company = info[0]; if(info[1] == "full") { backup.type = ProfileType::FullGame; } else if(info[1] == "demo") { backup.type = ProfileType::Demo; } else { continue; } auto ts = info[2].split('-'); if(ts.size() != 6) { continue; } backup.timestamp.year = std::stoi(ts[0]); backup.timestamp.month = std::stoi(ts[1]); backup.timestamp.day = std::stoi(ts[2]); backup.timestamp.hour = std::stoi(ts[3]); backup.timestamp.minute = std::stoi(ts[4]); backup.timestamp.second = std::stoi(ts[5]); Long num_entries = zip_get_num_entries(zip, ZIP_FL_UNCHANGED); if(num_entries == 0) { continue; } arrayReserve(backup.includedFiles, num_entries); for(Long i = 0; i < num_entries; i++) { arrayAppend(backup.includedFiles, InPlaceInit, zip_get_name(zip, i, ZIP_FL_UNCHANGED)); } arrayAppend(_backups, std::move(backup)); } } auto ProfileManager::deleteBackup(std::size_t index) -> bool { if(!Utility::Directory::rm(Utility::Directory::join(_backupsDirectory, _backups[index].filename))) { _lastError = "Couldn't delete " + _backups[index].filename; return false; } auto file = _backups[index].filename; auto it = std::remove_if(_backups.begin(), _backups.end(), [&file](Backup& backup){return backup.filename == file;}); if(it != _backups.end()) { arrayRemoveSuffix(_backups, 1); } return true; } auto ProfileManager::restoreBackup(std::size_t index) -> bool { const Backup& backup = _backups[index]; auto error_format = "Extraction of file {} failed: {}"_s; int error_code = 0; zip_t* zip = nullptr; zip = zip_open(Utility::Directory::join(_backupsDirectory, backup.filename).c_str(), ZIP_RDONLY, &error_code); if(zip == nullptr) { zip_error_t error; zip_error_init_with_code(&error, error_code); _lastError = zip_error_strerror(&error); return false; } Containers::ScopeGuard zip_guard{zip, zip_close}; for(Containers::StringView file : backup.includedFiles) { FILE* out = std::fopen(Utility::Directory::join(_saveDirectory, file).c_str(), "wb"); if(out == nullptr) { _lastError = Utility::formatString(error_format.data(), file, std::strerror(errno)); return false; } Containers::ScopeGuard out_guard{out, std::fclose}; zip_file_t* zf = zip_fopen(zip, file.data(), ZIP_FL_ENC_GUESS); if(zf == nullptr) { _lastError = Utility::format(error_format.data(), file, zip_strerror(zip)); return false; } Containers::ScopeGuard zf_guard{zf, zip_fclose}; Containers::StaticArray<8192, char> buf{ValueInit}; Long bytes_read = 0; while((bytes_read = zip_fread(zf, buf.data(), buf.size())) > 0) { if(std::fwrite(buf.data(), sizeof(char), bytes_read, out) < static_cast(bytes_read)) { _lastError = Utility::format(error_format.data(), file, "not enough bytes written."); return false; } } if(bytes_read == -1) { _lastError = Utility::format(error_format.data(), file, "couldn't read bytes from archive."); return false; } } return true; }