using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
using StardewValley;
namespace StardewModdingAPI.Mods.SaveBackup
{
/// The main entry point for the mod.
public class ModEntry : Mod
{
/*********
** Fields
*********/
/// The number of backups to keep.
private readonly int BackupsToKeep = 10;
/// The absolute path to the folder in which to store save backups.
private readonly string BackupFolder = Path.Combine(Constants.GamePath, "save-backups");
/// A unique label for the save backup to create.
private readonly string BackupLabel = $"{DateTime.UtcNow:yyyy-MM-dd} - SMAPI {Constants.ApiVersion} with Stardew Valley {Game1.version}";
/// The name of the save archive to create.
private string FileName => $"{this.BackupLabel}.zip";
/*********
** Public methods
*********/
/// The mod entry point, called after the mod is first loaded.
/// Provides simplified APIs for writing mods.
public override void Entry(IModHelper helper)
{
try
{
// init backup folder
DirectoryInfo backupFolder = new(this.BackupFolder);
backupFolder.Create();
// back up & prune saves
Task
.Run(() => this.CreateBackup(backupFolder))
.ContinueWith(_ => this.PruneBackups(backupFolder, this.BackupsToKeep));
}
catch (Exception ex)
{
this.Monitor.Log($"Error backing up saves: {ex}", LogLevel.Error);
}
}
/*********
** Private methods
*********/
/// Back up the current saves.
/// The folder containing save backups.
private void CreateBackup(DirectoryInfo backupFolder)
{
try
{
// get target path
FileInfo targetFile = new(Path.Combine(backupFolder.FullName, this.FileName));
DirectoryInfo fallbackDir = new(Path.Combine(backupFolder.FullName, this.BackupLabel));
if (targetFile.Exists || fallbackDir.Exists)
{
this.Monitor.Log("Already backed up today.");
return;
}
// copy saves to fallback directory (ignore non-save files/folders)
DirectoryInfo savesDir = new(Constants.SavesPath);
if (!this.RecursiveCopy(savesDir, fallbackDir, entry => this.MatchSaveFolders(savesDir, entry), copyRoot: false))
{
this.Monitor.Log("No saves found.");
return;
}
// compress backup if possible
if (!this.TryCompressDir(fallbackDir.FullName, targetFile, out Exception? compressError))
{
this.Monitor.Log(Constants.TargetPlatform != GamePlatform.Android
? $"Backed up to {fallbackDir.FullName}." // expected to fail on Android
: $"Backed up to {fallbackDir.FullName}. Couldn't compress backup:\n{compressError}"
);
}
else
{
this.Monitor.Log($"Backed up to {targetFile.FullName}.");
fallbackDir.Delete(recursive: true);
}
}
catch (Exception ex)
{
this.Monitor.Log("Couldn't back up saves (see log file for details).", LogLevel.Warn);
this.Monitor.Log(ex.ToString());
}
}
/// Remove old backups if we've exceeded the limit.
/// The folder containing save backups.
/// The number of backups to keep.
private void PruneBackups(DirectoryInfo backupFolder, int backupsToKeep)
{
try
{
var oldBackups = backupFolder
.GetFileSystemInfos()
.OrderByDescending(p => p.CreationTimeUtc)
.Skip(backupsToKeep);
foreach (FileSystemInfo entry in oldBackups)
{
try
{
this.Monitor.Log($"Deleting {entry.Name}...");
if (entry is DirectoryInfo folder)
folder.Delete(recursive: true);
else
entry.Delete();
}
catch (Exception ex)
{
this.Monitor.Log($"Error deleting old save backup '{entry.Name}': {ex}", LogLevel.Error);
}
}
}
catch (Exception ex)
{
this.Monitor.Log("Couldn't remove old backups (see log file for details).", LogLevel.Warn);
this.Monitor.Log(ex.ToString());
}
}
/// Try to create a compressed zip file for a directory.
/// The directory path to zip.
/// The destination file to create.
/// The error which occurred trying to compress, if applicable. This is if compression isn't supported on this platform.
/// Returns whether compression succeeded.
private bool TryCompressDir(string sourcePath, FileInfo destination, [NotNullWhen(false)] out Exception? error)
{
try
{
ZipFile.CreateFromDirectory(sourcePath, destination.FullName, CompressionLevel.Fastest, false);
error = null;
return true;
}
catch (Exception ex)
{
error = ex;
return false;
}
}
/// Recursively copy a directory or file.
/// The file or folder to copy.
/// The folder to copy into.
/// Whether to copy the root folder itself, or false to only copy its contents.
/// A filter which matches the files or directories to copy, or null to copy everything.
/// Derived from the SMAPI installer code.
/// Returns whether any files were copied.
private bool RecursiveCopy(FileSystemInfo source, DirectoryInfo targetFolder, Func? filter, bool copyRoot = true)
{
if (!source.Exists || filter?.Invoke(source) == false)
return false;
bool anyCopied = false;
switch (source)
{
case FileInfo sourceFile:
targetFolder.Create();
sourceFile.CopyTo(Path.Combine(targetFolder.FullName, sourceFile.Name));
anyCopied = true;
break;
case DirectoryInfo sourceDir:
DirectoryInfo targetSubfolder = copyRoot ? new DirectoryInfo(Path.Combine(targetFolder.FullName, sourceDir.Name)) : targetFolder;
foreach (var entry in sourceDir.EnumerateFileSystemInfos())
anyCopied = this.RecursiveCopy(entry, targetSubfolder, filter) || anyCopied;
break;
default:
throw new NotSupportedException($"Unknown filesystem info type '{source.GetType().FullName}'.");
}
return anyCopied;
}
/// A copy filter which matches save folders.
/// The folder containing save folders.
/// The current entry to check under .
private bool MatchSaveFolders(DirectoryInfo savesFolder, FileSystemInfo entry)
{
// only need to filter top-level entries
string? parentPath = (entry as FileInfo)?.DirectoryName ?? (entry as DirectoryInfo)?.Parent?.FullName;
if (parentPath != savesFolder.FullName)
return true;
// match folders with Name_ID format
return
entry is DirectoryInfo
&& ulong.TryParse(entry.Name.Split('_').Last(), out _);
}
}
}