Move LoadProfiles and DeleteProfiles to backend

pull/32/head
Miepee 4 years ago
parent fcdecbd36c
commit 56cb5528ce

@ -49,7 +49,7 @@ internal static class MainClass
{ {
string osRelease = File.ReadAllText("/etc/os-release"); string osRelease = File.ReadAllText("/etc/os-release");
Regex lineRegex = new Regex(".*=.*"); Regex lineRegex = new Regex(".*=.*");
var results = lineRegex.Matches(osRelease).Cast<Match>().ToList(); var results = lineRegex.Matches(osRelease).ToList();
var version = results.FirstOrDefault(x => x.Value.Contains("VERSION")); var version = results.FirstOrDefault(x => x.Value.Contains("VERSION"));
log.Info("Current Distro: " + results.FirstOrDefault(x => x.Value.Contains("NAME"))?.Value.Substring(5).Replace("\"", "") + log.Info("Current Distro: " + results.FirstOrDefault(x => x.Value.Contains("NAME"))?.Value.Substring(5).Replace("\"", "") +
(version == null ? "" : " " + version.Value.Substring(8).Replace("\"", ""))); (version == null ? "" : " " + version.Value.Substring(8).Replace("\"", "")));

@ -132,6 +132,15 @@ namespace AM2RLauncher
if (!isCurrentVersionOutdated) if (!isCurrentVersionOutdated)
return; return;
// For mac, we just show a message box that a new version is available, because I don't want to support for it yet
// hardcoded string, since also temporarily until it gets supported one day
if (OS.IsMac)
{
MessageBox.Show("Your current version is outdated! The newest version is " + onlineVersion + "." +
"Please recompile AM2RLauncher again or disable auto-updating");
return;
}
log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + "."); log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + ".");
string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/"; string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/";

@ -31,7 +31,7 @@ namespace AM2RLauncher
/// </summary> /// </summary>
private async void PlayButtonLoadComplete(object sender, EventArgs e) private async void PlayButtonLoadComplete(object sender, EventArgs e)
{ {
LoadProfiles(); LoadProfilesAndAdjustLists();
if (!Profile.IsPatchDataCloned() || !(bool)autoUpdateAM2RCheck.Checked) if (!Profile.IsPatchDataCloned() || !(bool)autoUpdateAM2RCheck.Checked)
return; return;
@ -92,7 +92,7 @@ namespace AM2RLauncher
{ {
progressBar.Visible = false; progressBar.Visible = false;
progressLabel.Visible = false; progressLabel.Visible = false;
LoadProfiles(); LoadProfilesAndAdjustLists();
} }
// Handling for updates - if current version does not match PatchData version, rename folder so that we attempt to install! // Handling for updates - if current version does not match PatchData version, rename folder so that we attempt to install!
@ -144,7 +144,7 @@ namespace AM2RLauncher
profileDropDown.SelectedIndex = 0; profileDropDown.SelectedIndex = 0;
LoadProfiles(); LoadProfilesAndAdjustLists();
} }
} }
@ -160,6 +160,9 @@ namespace AM2RLauncher
// State Check // State Check
UpdateStateMachine(); UpdateStateMachine();
// Check if 1.1 is installed by forcing invalidation
Profile.Is11Installed(true);
switch (updateState) switch (updateState)
{ {
#region Download #region Download
@ -240,7 +243,7 @@ namespace AM2RLauncher
SetPlayButtonState(UpdateState.Install); SetPlayButtonState(UpdateState.Install);
// This needs to be run BEFORE the state check so that the Mod Settings tab doesn't weird out // This needs to be run BEFORE the state check so that the Mod Settings tab doesn't weird out
LoadProfiles(); LoadProfilesAndAdjustLists();
// Do a state check // Do a state check
UpdateStateMachine(); UpdateStateMachine();
@ -438,7 +441,7 @@ namespace AM2RLauncher
progressBar.MaxValue = transferProgress.TotalObjects; progressBar.MaxValue = transferProgress.TotalObjects;
if (currentGitObject >= transferProgress.ReceivedObjects) if (currentGitObject >= transferProgress.ReceivedObjects)
return; return;
progressLabel.Text = Language.Text.ProgressbarProgress + " " + transferProgress.ReceivedObjects + " (" + (int)transferProgress.ReceivedBytes / 1000000 + "MB) / " + transferProgress.TotalObjects + " objects"; progressLabel.Text = Language.Text.ProgressbarProgress + " " + transferProgress.ReceivedObjects + " (" + ((int)transferProgress.ReceivedBytes / 1000000) + "MB) / " + transferProgress.TotalObjects + " objects";
currentGitObject = transferProgress.ReceivedObjects; currentGitObject = transferProgress.ReceivedObjects;
progressBar.Value = transferProgress.ReceivedObjects; progressBar.Value = transferProgress.ReceivedObjects;
}); });
@ -461,7 +464,7 @@ namespace AM2RLauncher
return; return;
} }
// Check if xdelta is installed on linux // Check if xdelta is installed on linux
if ((OS.IsUnix) && !CrossPlatformOperations.CheckIfXdeltaIsInstalled()) if (OS.IsUnix && !CrossPlatformOperations.CheckIfXdeltaIsInstalled())
{ {
MessageBox.Show(Language.Text.XdeltaNotFound, Language.Text.WarningWindowTitle, MessageBoxButtons.OK); MessageBox.Show(Language.Text.XdeltaNotFound, Language.Text.WarningWindowTitle, MessageBoxButtons.OK);
SetApkButtonState(ApkButtonState.Create); SetApkButtonState(ApkButtonState.Create);
@ -626,11 +629,11 @@ namespace AM2RLauncher
else else
{ {
log.Error("User did not supply valid input. Cancelling import."); log.Error("User did not supply valid input. Cancelling import.");
LoadProfiles(); LoadProfilesAndAdjustLists();
return; return;
} }
LoadProfiles(); LoadProfilesAndAdjustLists();
settingsProfileDropDown.SelectedIndex = profileList.FindIndex(p => p.Name == addedProfile.Name); settingsProfileDropDown.SelectedIndex = profileList.FindIndex(p => p.Name == addedProfile.Name);
if (settingsProfileDropDown.SelectedIndex == -1) if (settingsProfileDropDown.SelectedIndex == -1)
settingsProfileDropDown.SelectedIndex = 0; settingsProfileDropDown.SelectedIndex = 0;
@ -653,12 +656,11 @@ namespace AM2RLauncher
/// </summary> /// </summary>
private void SaveButtonClickEvent(object sender, EventArgs e) private void SaveButtonClickEvent(object sender, EventArgs e)
{ {
if (IsProfileIndexValid()) if (!IsProfileIndexValid())
{ return;
log.Info("User opened the save directory for profile " + profileList[settingsProfileDropDown.SelectedIndex].Name + ", which is " + profileList[settingsProfileDropDown.SelectedIndex].SaveLocation); log.Info("User opened the save directory for profile " + profileList[settingsProfileDropDown.SelectedIndex].Name + ", which is " + profileList[settingsProfileDropDown.SelectedIndex].SaveLocation);
CrossPlatformOperations.OpenFolder(profileList[settingsProfileDropDown.SelectedIndex].SaveLocation); CrossPlatformOperations.OpenFolder(profileList[settingsProfileDropDown.SelectedIndex].SaveLocation);
} }
}
/// <summary> /// <summary>
/// Enabled / disables <see cref="updateModButton"/> and <see cref="deleteModButton"/> accordingly. /// Enabled / disables <see cref="updateModButton"/> and <see cref="deleteModButton"/> accordingly.
@ -775,10 +777,11 @@ namespace AM2RLauncher
if (profileDropDown.SelectedIndex == -1 && profileDropDown.Items.Count == 0) return; if (profileDropDown.SelectedIndex == -1 && profileDropDown.Items.Count == 0) return;
profileIndex = profileDropDown.SelectedIndex; profileIndex = profileDropDown.SelectedIndex;
log.Info("profileDropDown.SelectedIndex has been changed to " + profileIndex + "."); log.Debug("profileDropDown.SelectedIndex has been changed to " + profileIndex + ".");
profileAuthorLabel.Text = Language.Text.Author + " " + profileList[profileDropDown.SelectedIndex].Author; profileAuthorLabel.Text = Language.Text.Author + " " + profileList[profileDropDown.SelectedIndex].Author;
profileVersionLabel.Text = Language.Text.VersionLabel + " " + profileList[profileDropDown.SelectedIndex].Version; profileVersionLabel.Text = Language.Text.VersionLabel + " " + profileList[profileDropDown.SelectedIndex].Version;
// TODO: only write this on application quit
CrossPlatformOperations.WriteToConfig("ProfileIndex", profileIndex.ToString()); CrossPlatformOperations.WriteToConfig("ProfileIndex", profileIndex.ToString());
if (profileDropDown.SelectedIndex != 0 && (profileList[profileDropDown.SelectedIndex].SaveLocation == "%localappdata%/AM2R" || if (profileDropDown.SelectedIndex != 0 && (profileList[profileDropDown.SelectedIndex].SaveLocation == "%localappdata%/AM2R" ||
@ -788,7 +791,6 @@ namespace AM2RLauncher
saveWarningLabel.Visible = false; saveWarningLabel.Visible = false;
UpdateStateMachine(); UpdateStateMachine();
} }
/// <summary>Gets called when user selects a different item from <see cref="languageDropDown"/> and writes that to the config.</summary> /// <summary>Gets called when user selects a different item from <see cref="languageDropDown"/> and writes that to the config.</summary>
@ -940,7 +942,7 @@ namespace AM2RLauncher
if (result == DialogResult.Ok) if (result == DialogResult.Ok)
{ {
log.Info("User did not cancel. Proceeding to delete " + profile); log.Info("User did not cancel. Proceeding to delete " + profile);
DeleteProfile(profile); DeleteProfileAndAdjustLists(profile);
log.Info(profile + " has been deleted"); log.Info(profile + " has been deleted");
MessageBox.Show(Language.Text.DeleteModButtonSuccess.Replace("$NAME", profile.Name), Language.Text.SuccessWindowTitle); MessageBox.Show(Language.Text.DeleteModButtonSuccess.Replace("$NAME", profile.Name), Language.Text.SuccessWindowTitle);
} }
@ -1020,7 +1022,7 @@ namespace AM2RLauncher
if (result == DialogResult.Ok) if (result == DialogResult.Ok)
{ {
// Delete profile // Delete profile
DeleteProfile(currentProfile); DeleteProfileAndAdjustLists(currentProfile);
// Rename directory to take the old one's place // Rename directory to take the old one's place
string originalFolder = modsDir + "/" + extractedName.Replace("_new", ""); string originalFolder = modsDir + "/" + extractedName.Replace("_new", "");
@ -1047,7 +1049,7 @@ namespace AM2RLauncher
{ {
// File cleanup // File cleanup
HelperMethods.DeleteDirectory(modsDir + "/" + extractedName); HelperMethods.DeleteDirectory(modsDir + "/" + extractedName);
LoadProfiles(); LoadProfilesAndAdjustLists();
return; return;
} }
@ -1057,7 +1059,7 @@ namespace AM2RLauncher
} }
ProfileXML currentSelectedProfile = profileList[settingsProfileDropDown.SelectedIndex]; ProfileXML currentSelectedProfile = profileList[settingsProfileDropDown.SelectedIndex];
LoadProfiles(); LoadProfilesAndAdjustLists();
settingsProfileDropDown.SelectedIndex = profileList.FindIndex(p => p.Name == currentSelectedProfile.Name); settingsProfileDropDown.SelectedIndex = profileList.FindIndex(p => p.Name == currentSelectedProfile.Name);
if (settingsProfileDropDown.SelectedIndex == -1) if (settingsProfileDropDown.SelectedIndex == -1)
settingsProfileDropDown.SelectedIndex = 0; settingsProfileDropDown.SelectedIndex = 0;

@ -1,6 +1,5 @@
using Eto.Drawing; using Eto.Drawing;
using System; using System;
using System.IO;
using AM2RLauncher.Core; using AM2RLauncher.Core;
using AM2RLauncher.Core.XML; using AM2RLauncher.Core.XML;
@ -52,7 +51,7 @@ namespace AM2RLauncher
else if (isProfileValid && profileList[profileIndex.Value].Installable == false) else if (isProfileValid && profileList[profileIndex.Value].Installable == false)
{ {
// We delete the profile, because we can't install it and it therefore holds no value! // We delete the profile, because we can't install it and it therefore holds no value!
DeleteProfile(profileList[profileIndex.Value]); DeleteProfileAndAdjustLists(profileList[profileIndex.Value]);
} }
// Otherwise, we still need to install. // Otherwise, we still need to install.
else else
@ -269,84 +268,17 @@ namespace AM2RLauncher
} }
/// <summary> /// <summary>
/// Deletes the given <paramref name="profile"/>. Reloads the <see cref="profileList"/> if <paramref name="reloadProfileList"/> is true. /// Loads valid profile entries and reloads the necessary UI components.
/// </summary> /// </summary>
private void DeleteProfile(ProfileXML profile, bool reloadProfileList = true) private void LoadProfilesAndAdjustLists()
{ {
log.Info("Attempting to delete profile " + profile.Name + "...");
// Delete folder in Mods
if (Directory.Exists(CrossPlatformOperations.CURRENTPATH + profile.DataPath))
{
HelperMethods.DeleteDirectory(CrossPlatformOperations.CURRENTPATH + profile.DataPath);
}
// Delete the zip file in Mods
if (File.Exists(CrossPlatformOperations.CURRENTPATH + profile.DataPath + ".zip"))
{
File.SetAttributes(CrossPlatformOperations.CURRENTPATH + profile.DataPath + ".zip", FileAttributes.Normal); // For some reason, it was set at read only, so we undo that here
File.Delete(CrossPlatformOperations.CURRENTPATH + profile.DataPath + ".zip");
}
// Delete folder in Profiles
if (Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/Profiles/" + profile.Name))
{
HelperMethods.DeleteDirectory(CrossPlatformOperations.CURRENTPATH + "/Profiles/" + profile.Name);
}
if (reloadProfileList)
LoadProfiles();
log.Info("Successfully deleted profile " + profile.Name + ".");
}
/// <summary>
/// Scans the PatchData and Mods folders for valid profile entries, and loads them.
/// </summary>
//TODO: Seperate this (and by extension, deleteProfile) from UI and backend
private void LoadProfiles()
{
log.Info("Loading profiles...");
// Reset loaded profiles // Reset loaded profiles
profileDropDown.Items.Clear(); profileDropDown.Items.Clear();
profileList.Clear(); profileList.Clear();
profileIndex = null; profileIndex = null;
// Check for and add the Community Updates profile // Load the profileList
if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/PatchData/profile.xml")) profileList = Profile.LoadProfiles();
{
profileList.Add(Serializer.Deserialize<ProfileXML>(File.ReadAllText(CrossPlatformOperations.CURRENTPATH + "/PatchData/profile.xml")));
profileList[0].DataPath = "/PatchData/data";
}
// Safety check to generate the Mods folder if it does not exist
if (!Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/Mods"))
Directory.CreateDirectory(CrossPlatformOperations.CURRENTPATH + "/Mods");
// Get Mods folder info
DirectoryInfo modsDir = new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/Mods");
// Add all extracted profiles in Mods to the profileList.
foreach (DirectoryInfo dir in modsDir.GetDirectories())
{
foreach (FileInfo file in dir.GetFiles())
{
if (file.Name != "profile.xml")
continue;
ProfileXML prof = Serializer.Deserialize<ProfileXML>(File.ReadAllText(dir.FullName + "/profile.xml"));
if (prof.Installable || Profile.IsProfileInstalled(prof)) // Safety check for non-installable profiles
{
prof.DataPath = "/Mods/" + dir.Name;
profileList.Add(prof);
}
else if (!Profile.IsProfileInstalled(prof)) // If not installable and isn't installed, remove it
{
prof.DataPath = "/Mods/" + dir.Name;
DeleteProfile(prof, false);
}
}
}
// Add profile names to the profileDropDown // Add profile names to the profileDropDown
foreach (ProfileXML profile in profileList) foreach (ProfileXML profile in profileList)
@ -383,8 +315,6 @@ namespace AM2RLauncher
settingsProfileDropDown.Items.AddRange(profileDropDown.Items); settingsProfileDropDown.Items.AddRange(profileDropDown.Items);
settingsProfileDropDown.SelectedIndex = profileDropDown.Items.Count != 0 ? 0 : -1; settingsProfileDropDown.SelectedIndex = profileDropDown.Items.Count != 0 ? 0 : -1;
log.Info("Loaded " + profileList.Count + " profile(s).");
// Refresh the author and version label on the main tab // Refresh the author and version label on the main tab
if (profileList.Count > 0) if (profileList.Count > 0)
{ {
@ -392,7 +322,20 @@ namespace AM2RLauncher
profileVersionLabel.Text = Language.Text.VersionLabel + " " + profileList[profileDropDown.SelectedIndex].Version; profileVersionLabel.Text = Language.Text.VersionLabel + " " + profileList[profileDropDown.SelectedIndex].Version;
} }
log.Info("Reloading UI components after loading successful.");
UpdateStateMachine(); UpdateStateMachine();
} }
/// <summary>
/// Deletes a profile and reloads the necessary UI components.
/// </summary>
/// <param name="profile">The profile to delete.</param>
private void DeleteProfileAndAdjustLists(ProfileXML profile)
{
Profile.DeleteProfile(profile);
LoadProfilesAndAdjustLists();
}
} }
} }

@ -10,7 +10,6 @@ using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
namespace AM2RLauncher namespace AM2RLauncher

@ -2,6 +2,7 @@
using LibGit2Sharp; using LibGit2Sharp;
using log4net; using log4net;
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
@ -44,13 +45,21 @@ public static class Profile
/// </summary> /// </summary>
private static string lastAM2R11ZipMD5 = ""; private static string lastAM2R11ZipMD5 = "";
/*/// <summary>
/// Checks if AM2R 1.1 has been installed already, aka if a valid AM2R 1.1 Zip exists.
/// </summary>
/// <returns><see langword="true"/> if yes, <see langword="false"/> if not.</returns>*/
/// <summary> /// <summary>
/// Checks if AM2R 1.1 has been installed already, aka if a valid AM2R 1.1 Zip exists. /// Checks if AM2R 1.1 has been installed already, aka if a valid AM2R 1.1 Zip exists.
/// </summary> /// </summary>
/// <returns><see langword="true"/> if yes, <see langword="false"/> if not.</returns> /// <param name="invalidateCache">Determines if the AM2R_11 Cache should be invalidated</param>
public static bool Is11Installed() /// <returns></returns>
public static bool Is11Installed(bool invalidateCache = false)
{ {
InvalidateAM2R11InstallCache(); // Only invalidate if we need to
if (invalidateCache) InvalidateAM2R11InstallCacheIfNecessary();
// If we have a cache, return that instead // If we have a cache, return that instead
if (isAM2R11InstalledCache != null) return isAM2R11InstalledCache.Value; if (isAM2R11InstalledCache != null) return isAM2R11InstalledCache.Value;
@ -73,9 +82,9 @@ public static class Profile
} }
/// <summary> /// <summary>
/// Invalidates <see cref="isAM2R11InstalledCache"/>. /// Invalidates <see cref="isAM2R11InstalledCache"/> if necessary.
/// </summary> /// </summary>
private static void InvalidateAM2R11InstallCache() private static void InvalidateAM2R11InstallCacheIfNecessary()
{ {
// If the file exists, and its hash matches with ours, don't invalidate // If the file exists, and its hash matches with ours, don't invalidate
if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/AM2R_11.zip") && if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/AM2R_11.zip") &&
@ -122,6 +131,92 @@ public static class Profile
} }
log.Info("Repository pulled successfully."); log.Info("Repository pulled successfully.");
} }
/*
/// <summary>
/// Scans the PatchData and Mods folders for valid profile entries, and loads them.
/// </summary>*/
/// <summary>
/// Scans the PatchData and Mods folders for valid profile entries, creates and returns a list of them.
/// </summary>
/// <returns>A <see cref="List{ProfileXML}"/> containing all valid profile entries.</returns>
public static List<ProfileXML> LoadProfiles()
{
log.Info("Loading profiles...");
List<ProfileXML> profileList = new List<ProfileXML>();
// Check for and add the Community Updates profile
if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/PatchData/profile.xml"))
{
ProfileXML profile = Serializer.Deserialize<ProfileXML>(File.ReadAllText(CrossPlatformOperations.CURRENTPATH + "/PatchData/profile.xml"));
profile.DataPath = "/PatchData/data";
profileList.Add(profile);
}
// Safety check to generate the Mods folder if it does not exist
if (!Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/Mods"))
Directory.CreateDirectory(CrossPlatformOperations.CURRENTPATH + "/Mods");
// Get Mods folder info
DirectoryInfo modsDir = new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/Mods");
// Add all extracted profiles in Mods to the profileList.
foreach (DirectoryInfo dir in modsDir.GetDirectories())
{
// If no profile.xml exists we don't add anything
if (!File.Exists(dir.FullName + "/profile.xml"))
continue;
ProfileXML prof = Serializer.Deserialize<ProfileXML>(File.ReadAllText(dir.FullName + "/profile.xml"));
// Safety check for non-installable profiles
if (prof.Installable || IsProfileInstalled(prof))
{
prof.DataPath = "/Mods/" + dir.Name;
profileList.Add(prof);
}
// If not installable and isn't installed, remove it
else if (!IsProfileInstalled(prof))
{
prof.DataPath = "/Mods/" + dir.Name;
DeleteProfile(prof);
}
}
log.Info("Loaded " + profileList.Count + " profile(s).");
return profileList;
}
/// <summary>
/// Deletes a profile from the Mods and Profiles folder.
/// </summary>
/// <param name="profile">The profile to delete.</param>
public static void DeleteProfile(ProfileXML profile)
{
log.Info("Attempting to delete profile " + profile.Name + "...");
// Delete folder in Mods
if (Directory.Exists(CrossPlatformOperations.CURRENTPATH + profile.DataPath))
{
HelperMethods.DeleteDirectory(CrossPlatformOperations.CURRENTPATH + profile.DataPath);
}
// Delete the zip file in Mods
if (File.Exists(CrossPlatformOperations.CURRENTPATH + profile.DataPath + ".zip"))
{
// For some reason, it was set at read only, so we undo that here
File.SetAttributes(CrossPlatformOperations.CURRENTPATH + profile.DataPath + ".zip", FileAttributes.Normal);
File.Delete(CrossPlatformOperations.CURRENTPATH + profile.DataPath + ".zip");
}
// Delete folder in Profiles
if (Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/Profiles/" + profile.Name))
{
HelperMethods.DeleteDirectory(CrossPlatformOperations.CURRENTPATH + "/Profiles/" + profile.Name);
}
log.Info("Successfully deleted profile " + profile.Name + ".");
}
/// <summary> /// <summary>
/// Installs <paramref name="profile"/>. /// Installs <paramref name="profile"/>.

Loading…
Cancel
Save