MassBuilderSaveTool/src/ProfileManager/ProfileManager.cpp

354 lines
12 KiB
C++

// 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 <https://www.gnu.org/licenses/>.
#include <cstdio>
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <regex>
#include <Corrade/Containers/ScopeGuard.h>
#include <Corrade/Containers/StaticArray.h>
#include <Corrade/Utility/Format.h>
#include <Corrade/Utility/Path.h>
#include <Corrade/Utility/String.h>
#include <zip.h>
#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<Profile> {
return _profiles;
}
auto ProfileManager::refreshProfiles() -> bool {
_profiles = Containers::Array<Profile>{};
using Utility::Path::ListFlag;
auto files = Utility::Path::list(_saveDirectory,
ListFlag::SkipSpecial|ListFlag::SkipDirectories|ListFlag::SkipDotAndDotDot);
if(!files) {
_lastError = _saveDirectory + " can't be opened.";
return false;
}
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);
};
auto files_view = files->except(files->end() - std::remove_if(files->begin(), files->end(), predicate));
for(const auto& file : files_view) {
Profile profile{Utility::Path::join(_saveDirectory, file)};
if(!profile.valid()) {
Utility::Warning{} << "Profile"_s << file << "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::Path::remove(Utility::Path::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::Path::remove(Utility::Path::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(&timestamp);
auto filename = Utility::format("{}_{}{:.2d}{:.2d}_{:.2d}{:.2d}{:.2d}.mbprofbackup",
Utility::String::replaceAll(_profiles[index].companyName().data(), " ", "_").c_str(),
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::Path::join(_backupsDirectory, filename).data(), 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::Path::toNativeSeparators(Utility::Path::join(_saveDirectory, _profiles[index].filename())).data(), 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::Path::exists(Utility::Path::join(_saveDirectory, build_filename))) {
continue;
}
zip_source_t* build_source = zip_source_file(zip, Utility::Path::toNativeSeparators(Utility::Path::join(_saveDirectory, build_filename)).data(), 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<Backup> {
return _backups;
}
void ProfileManager::refreshBackups() {
_backups = Containers::Array<Backup>{};
using Utility::Path::ListFlag;
auto files = Utility::Path::list(_backupsDirectory,
ListFlag::SkipSpecial|ListFlag::SkipDirectories|ListFlag::SkipDotAndDotDot);
if(!files) {
_lastError = _backupsDirectory + " can't be opened.";
return;
}
auto predicate = [](Containers::StringView file)->bool{
return !file.hasSuffix(".mbprofbackup"_s);
};
auto files_view = files->except(files->end() - std::remove_if(files->begin(), files->end(), predicate));
int error_code = 0;
zip_t* zip = nullptr;
for(Containers::StringView file : files_view) {
Backup backup;
backup.filename = file;
zip = zip_open(Utility::Path::join(_backupsDirectory, file).data(), ZIP_RDONLY, &error_code);
if(zip == nullptr) {
continue;
}
Containers::ScopeGuard guard{zip, zip_close};
Long num_entries = zip_get_num_entries(zip, ZIP_FL_UNCHANGED);
if(num_entries == 0) {
continue;
}
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::strtol(ts[0].data(), nullptr, 10);
backup.timestamp.month = std::strtol(ts[1].data(), nullptr, 10);
backup.timestamp.day = std::strtol(ts[2].data(), nullptr, 10);
backup.timestamp.hour = std::strtol(ts[3].data(), nullptr, 10);
backup.timestamp.minute = std::strtol(ts[4].data(), nullptr, 10);
backup.timestamp.second = std::strtol(ts[5].data(), nullptr, 10);
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::Path::remove(Utility::Path::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::Path::join(_backupsDirectory, backup.filename).data(), 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::Path::join(_saveDirectory, file).data(), "wb");
if(out == nullptr) {
_lastError = Utility::format(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<std::size_t>(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;
}