Files
MSCO/SaveSync.cs
T
2026-09-26 00:08:05 +02:00

90 lines
3.3 KiB
C#

using System.Collections.Generic;
using System.IO;
using MSCLoader;
using UnityEngine;
namespace MSCO
{
/// <summary>
/// Liest den Spielstand des Hosts und ersetzt beim Client den eigenen Spielstand
/// vorübergehend. Der Spielstand des Clients wird vorher gesichert und beim
/// nächsten Hauptmenü automatisch wiederhergestellt.
/// </summary>
public static class SaveSync
{
// Nur diese Dateien werden übertragen (options.txt etc. bleiben beim Spieler)
public static readonly string[] Files =
{
"defaultES2File.txt", "items.txt", "meshsave.txt", "graveyard.txt", "notepad.txt"
};
static string SaveDir { get { return Application.persistentDataPath; } }
static string BackupDir { get { return Path.Combine(SaveDir, "MSCO_Backup"); } }
static string Marker { get { return Path.Combine(BackupDir, "backup_active"); } }
public static bool HasBackup { get { return File.Exists(Marker); } }
public static List<KeyValuePair<string, byte[]>> ReadLocalSave()
{
var result = new List<KeyValuePair<string, byte[]>>();
foreach (string name in Files)
{
string path = Path.Combine(SaveDir, name);
if (File.Exists(path))
result.Add(new KeyValuePair<string, byte[]>(name, File.ReadAllBytes(path)));
}
return result;
}
/// <summary>Eigenen Spielstand sichern (nur einmal) und die Spielstand-Dateien leeren.</summary>
public static void BeginReceive()
{
if (!HasBackup)
{
Directory.CreateDirectory(BackupDir);
foreach (string name in Files)
{
string path = Path.Combine(SaveDir, name);
if (File.Exists(path)) File.Copy(path, Path.Combine(BackupDir, name), true);
}
File.WriteAllText(Marker, "MSCO backup of the client's own save. Restored automatically.");
ModConsole.Print("[MSCO] Own save backed up to " + BackupDir);
}
DeleteSaveFiles();
}
public static void WriteFile(string name, byte[] data)
{
// Nur bekannte Dateinamen erlauben, damit der Host nichts anderes überschreiben kann
if (System.Array.IndexOf(Files, name) < 0)
{
ModConsole.Warning("[MSCO] Ignored unexpected save file: " + name);
return;
}
File.WriteAllBytes(Path.Combine(SaveDir, name), data);
}
public static void RestoreBackup()
{
if (!HasBackup) return;
DeleteSaveFiles();
foreach (string name in Files)
{
string backup = Path.Combine(BackupDir, name);
if (File.Exists(backup)) File.Copy(backup, Path.Combine(SaveDir, name), true);
}
Directory.Delete(BackupDir, true);
ModConsole.Print("[MSCO] Own save restored.");
}
static void DeleteSaveFiles()
{
foreach (string name in Files)
{
string path = Path.Combine(SaveDir, name);
if (File.Exists(path)) File.Delete(path);
}
}
}
}