using System; using System.IO; using System.IO.Compression; using System.Linq; using StardewModdingAPI; using StardewModdingAPI.Events; namespace Omegasis.SaveBackup { /// The mod entry point. public class SaveBackup : Mod { /********* ** Properties *********/ /// The folder path containing the game's app data. private static readonly string AppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley"); /// The folder path containing the game's saves. private static readonly string SavesPath = Path.Combine(SaveBackup.AppDataPath, "Saves"); /// The folder path containing backups of the save before the player starts playing. private static readonly string PrePlayBackupsPath = Path.Combine(SaveBackup.AppDataPath, "Backed_Up_Saves", "Pre_Play_Saves"); /// The folder path containing nightly backups of the save. private static readonly string NightlyBackupsPath = Path.Combine(SaveBackup.AppDataPath, "Backed_Up_Saves", "Nightly_InGame_Saves"); /// The number of save backups to keep for each type. private int SaveCount = 30; /********* ** 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) { this.LoadConfig(); this.WriteConfig(); this.BackupSaves(SaveBackup.PrePlayBackupsPath); TimeEvents.DayOfMonthChanged += this.TimeEvents_DayOfMonthChanged; } /********* ** Private methods *********/ /// The method invoked when changes. /// The event sender. /// The event data. private void TimeEvents_DayOfMonthChanged(object sender, EventArgs e) { this.BackupSaves(SaveBackup.NightlyBackupsPath); } /// Back up saves to the specified folder. /// The folder path in which to generate saves. private void BackupSaves(string folderPath) { // back up saves Directory.CreateDirectory(folderPath); ZipFile.CreateFromDirectory(SaveBackup.SavesPath, Path.Combine(folderPath, $"backup-{DateTime.Now:yyyyMMdd'-'HHmmss}.zip")); // delete old backups new DirectoryInfo(folderPath) .EnumerateFiles() .OrderByDescending(f => f.CreationTime) .Skip(this.SaveCount) .ToList() .ForEach(file => file.Delete()); } /// Load the configuration settings. private void LoadConfig() { var path = Path.Combine(Helper.DirectoryPath, "AutoBackup_data.txt"); if (File.Exists(path)) { string[] text = File.ReadAllLines(path); this.SaveCount = Convert.ToInt32(text[3]); } } /// Save the configuration settings. private void WriteConfig() { string path = Path.Combine(Helper.DirectoryPath, "AutoBackup_data.txt"); string[] text = new string[20]; text[0] = "Player: AutoBackup Config:"; text[1] = "===================================================================================="; text[2] = "Number of Backups to Keep:"; text[3] = this.SaveCount.ToString(); File.WriteAllLines(path, text); } } }