Skip to content

Commit

Permalink
Finalized Audio split
Browse files Browse the repository at this point in the history
Redid config system
  • Loading branch information
Sarah Hawthorne committed Sep 3, 2020
1 parent 3ad534c commit 3e20087
Show file tree
Hide file tree
Showing 17 changed files with 298 additions and 181 deletions.
11 changes: 5 additions & 6 deletions Apex Launcher/Apex Launcher.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,10 @@
<ApplicationIcon>giratina.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>false</SignAssembly>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>
</AssemblyOriginatorKeyFile>
<AssemblyOriginatorKeyFile>Properties\LauncherKey.pfx</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
Expand All @@ -78,6 +77,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Config.cs" />
<Compile Include="Forms\DownloadForm.cs">
<SubType>Form</SubType>
</Compile>
Expand Down Expand Up @@ -148,6 +148,7 @@
<EmbeddedResource Include="Forms\TextEntryForm.resx">
<DependentUpon>TextEntryForm.cs</DependentUpon>
</EmbeddedResource>
<None Include="Properties\LauncherKey.pfx" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
Expand All @@ -165,11 +166,9 @@
<EmbeddedResource Include="config.txt" />
</ItemGroup>
<ItemGroup>
<Content Include="VersionManifest.xml" />
<Content Include="VersionManifestAudio.xml" />
<Content Include="giratina.ico" />
<Content Include="VersionManifest.xml">
<SubType>Designer</SubType>
</Content>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
Expand Down
104 changes: 104 additions & 0 deletions Apex Launcher/Config.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Apex_Launcher {
public static class Config {
private static string Filepath => Path.Combine(Directory.GetCurrentDirectory(), "config.txt");

private static VersionGameFiles _currentVersion;
public static VersionGameFiles CurrentVersion {
get {
return _currentVersion;
}
set {
_currentVersion = value;
SaveConfig();
}
}

private static VersionAudio _currentVersionAudio;
public static VersionAudio CurrentAudioVersion {
get {
return _currentVersionAudio;
}
set {
_currentVersionAudio = value;
SaveConfig();
}
}

private static string _installPath;
public static string InstallPath {
get {
if (string.IsNullOrEmpty(_installPath)) return Directory.GetCurrentDirectory();
return _installPath;
}
set {
_installPath = value;
SaveConfig();
}
}

private static bool _keepLauncherOpen;
public static bool KeepLauncherOpen {
get {
return _keepLauncherOpen;
}
set {
_keepLauncherOpen = value;
SaveConfig();
}
}

private static bool _disableAudioDownload;
public static bool DisableAudioDownload {
get {
return _disableAudioDownload;
}
set {
_disableAudioDownload = value;
SaveConfig();
}
}

public static void LoadConfig() {
if (!File.Exists(Filepath)) CreateConfig();
foreach (string line in File.ReadAllLines(Filepath)) {
if (line.Length == 0 || new[] { '\n', ' ', '#' }.Contains(line[0]) || !line.Contains('=')) continue;
string[] split = line.Split('=');
string param = split[0].Trim();
string value = split[1].Trim();

foreach (PropertyInfo pi in typeof(Config).GetProperties()) {
if (pi.Name.ToLower() == param) {
try {
object v = null;
if (pi.PropertyType.IsAssignableFrom(typeof(IDownloadable))) {
if (pi.PropertyType == typeof(VersionGameFiles)) v = VersionGameFiles.FromString(value);
if (pi.PropertyType == typeof(VersionAudio)) v = VersionAudio.FromString(value);
} else pi.SetValue(null, Convert.ChangeType(value, pi.PropertyType));
} catch (Exception) {
pi.SetValue(null, default);
}
break;
}
}
}
}

public static void SaveConfig() {
List<string> lines = new List<string>();
foreach (PropertyInfo pi in typeof(Config).GetProperties()) lines.Add($"{pi.Name}={pi.GetValue(null)}");
File.WriteAllLines(Filepath, lines);
}

public static void CreateConfig() {
using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Apex_Launcher.config.txt");
using FileStream fileStream = new FileStream(Filepath, FileMode.CreateNew);
for (int i = 0; i < stream.Length; i++) fileStream.WriteByte((byte)stream.ReadByte());
}
}
}
128 changes: 76 additions & 52 deletions Apex Launcher/Forms/DownloadForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,39 @@ namespace Apex_Launcher {
public partial class DownloadForm : Form {
private readonly List<IDownloadable> downloadQueue;
private Thread dlThread = null;
private string currentFilepath;
private readonly VersionGameFiles BaseVersion;
private readonly VersionGameFiles MostRecent;

public bool Downloading { get; private set; }

[Obsolete("Switch to download queueing")]
public DownloadForm(IDownloadable v) : this(new List<IDownloadable>() { v }) { }

public DownloadForm(List<IDownloadable> downloads) {
InitializeComponent();
downloadQueue = new List<IDownloadable>();
foreach (IDownloadable d in downloads) {
if (d is VersionGameFiles) {
if (MostRecent == null || d.GreaterThan(MostRecent)) MostRecent = d as VersionGameFiles;
}
if (d.Prerequisite != null && d.Prerequisite.NewerThanDownloaded()) downloadQueue.Add(d.Prerequisite);
else if (d is VersionGameFiles) {
VersionGameFiles vgf = d as VersionGameFiles;
if (!vgf.IsPatch) BaseVersion = vgf;
}
downloadQueue.Add(d);
}

Aborted += DownloadForm_Aborted;
QueueComplete += DownloadForm_QueueComplete;
}

private void DownloadForm_QueueComplete(object sender, EventArgs e) {
if (MostRecent != null) {
Config.CurrentVersion = MostRecent;
Config.CurrentAudioVersion = MostRecent.MinimumAudioVersion;
}

Program.Launcher.SetGameVersion(MostRecent);
Program.Launcher.UpdateStatus("Ready to launch");
}

private void DownloadForm_Aborted(object sender, EventArgs e) {
Expand All @@ -37,8 +56,9 @@ private void DownloadForm_Aborted(object sender, EventArgs e) {

public void StartDownload() {
Downloading = true;
dlThread = new Thread(Download);
dlThread.IsBackground = true;
dlThread = new Thread(Download) {
IsBackground = true
};
dlThread.SetApartmentState(ApartmentState.STA);
dlThread.Start();
}
Expand All @@ -48,13 +68,14 @@ public void Download() {
bool allFinished = true;
foreach (IDownloadable download in downloadQueue) {
string Source = download.Location;
string Destination = Path.Combine(Program.GetInstallPath(), "Versions", download.ToString());
string filepath = Destination + ".zip";
string Destination = Path.Combine(Config.InstallPath, "Versions", download.ToString());
currentFilepath = Destination + ".zip";

Program.Launcher.UpdateStatus("Downloading " + download.ToString());
Directory.CreateDirectory(Destination);
bool succeeded = true;

// Download
HttpWebRequest filereq = (HttpWebRequest)WebRequest.Create(Source);
HttpWebResponse fileresp = null;
try {
Expand All @@ -69,23 +90,24 @@ public void Download() {
return;
}
if (filereq.ContentLength > 0) fileresp.ContentLength = filereq.ContentLength;
if (fileresp.ContentLength <= 0) {
MessageBox.Show($"Could not access file {download}. Package skipped.");
continue;
}
using (Stream dlstream = fileresp.GetResponseStream()) {
using FileStream outputStream = new FileStream(filepath, FileMode.OpenOrCreate);
using FileStream outputStream = new FileStream(currentFilepath, FileMode.OpenOrCreate);
int buffersize = 10000;
try {
long bytesRead = 0;
int length = 1;
while (length > 0) {
byte[] buffer = new Byte[buffersize];
byte[] buffer = new byte[buffersize];
length = dlstream.Read(buffer, 0, buffersize);
bytesRead += length;
outputStream.Write(buffer, 0, length);
UpdateProgress((int)(100 * bytesRead / fileresp.ContentLength));
UpdateProgress(Convert.ToInt32(100F * bytesRead / fileresp.ContentLength));
UpdateProgressText(
"Downloading " + download.ToString() +
" (Package " + (downloadQueue.IndexOf(download) + 1) + "/" + downloadQueue.Count + ") " +
(bytesRead / 1048576) + "/" + (fileresp.ContentLength / 1048576) +
" MB (" + Convert.ToInt16(100 * (double)bytesRead / fileresp.ContentLength, Program.Culture) + "%)..."
$"Downloading {download} (Package {downloadQueue.IndexOf(download) + 1}/{downloadQueue.Count}) {(bytesRead / 1048576)}/{(fileresp.ContentLength / 1048576)} MB (" + Convert.ToInt16(100 * (double)bytesRead / fileresp.ContentLength, Program.Culture) + "%)..."
);
}
} catch (WebException e) {
Expand All @@ -105,47 +127,52 @@ public void Download() {
}
}

if (succeeded) {
Program.Launcher.UpdateStatus("Extracting version " + download.ToString());
try {
if (Directory.Exists(Destination)) Directory.Delete(Destination, true);
UpdateProgressText("Download " + (downloadQueue.IndexOf(download) + 1) + "/" + downloadQueue.Count +
" completed. Extracting...");
ZipFile.ExtractToDirectory(filepath, Destination);

if (download is VersionGameFiles) {
VersionGameFiles vgf = download as VersionGameFiles;
if (vgf.IsPatch) {
UpdateProgressText("Patching...");
string versionpath = Program.GetInstallPath() + "\\Versions\\" + download.Prerequisite.ToString();
RecursiveCopy(versionpath, Destination, false);
}
}
} catch (InvalidDataException) {
MessageBox.Show(
"Could not unzip file\n" + Destination + ".zip.\nThe file appears to be invalid. Please report this issue. In the meantime, try a manual download.",
"Apex Launcher Error",
MessageBoxButtons.OK,
MessageBoxIcon.Warning
);
}
File.Delete(filepath);
} else {
if (!succeeded) {
allFinished = false;
MessageBox.Show(
"The download couldn't be completed. Check your internet connection. If you think this is a program error, please report this to the Launcher's GitHub page."
);
break;
}

// Extraction
Program.Launcher.UpdateStatus("Extracting " + download.ToString());
try {
if (Directory.Exists(Destination)) Directory.Delete(Destination, true);
UpdateProgressText("Download " + (downloadQueue.IndexOf(download) + 1) + "/" + downloadQueue.Count +
" completed. Extracting...");
ZipFile.ExtractToDirectory(currentFilepath, Destination);
} catch (InvalidDataException) {
MessageBox.Show(
"Could not unzip file\n" + Destination + ".zip.\nThe file appears to be invalid. Please report this issue. In the meantime, try a manual download.",
"Apex Launcher Error",
MessageBoxButtons.OK,
MessageBoxIcon.Warning
);

continue;
}

// Patching
if (download is VersionGameFiles) {
VersionGameFiles vgf = download as VersionGameFiles;
if (vgf.IsPatch) {
UpdateProgressText("Patching...");
string versionpath = Path.Combine(Config.InstallPath, "Versions", download.Prerequisite.ToString());
RecursiveCopy(versionpath, Destination, false);
}
} else if (download is VersionAudio) {
VersionAudio va = download as VersionAudio;
string versionpath = Path.Combine(Config.InstallPath, "Versions", BaseVersion.ToString());
RecursiveCopy(Destination, versionpath, true);
}
File.Delete(currentFilepath);
}
if (allFinished) {
QueueComplete?.Invoke(this, new EventArgs());
/*Program.SetParameter("currentversion", v.ToString());
Program.Launcher.SetGameVersion(v);
Program.Launcher.UpdateStatus("Ready to launch");*/
}
CloseForm();
} catch (ThreadAbortException) { } catch (Exception e) {
} catch (ThreadAbortException) { } catch (ThreadInterruptedException) { } catch (Exception e) {
new ErrorCatcher(e).ShowDialog();
CloseForm();
}
Expand All @@ -155,16 +182,16 @@ public void Download() {
public void UpdateProgress(int progress) {
if (DownloadProgressBar.InvokeRequired) {
UP d = UpdateProgress;
this.Invoke(d, new object[] { progress });
} else DownloadProgressBar.Value = progress;
Invoke(d, new object[] { progress });
} else if (progress >= 0) DownloadProgressBar.Value = progress;
}

public delegate void UPT(string message);
public void UpdateProgressText(string message) {
if (ProgressLabel.InvokeRequired) {
UPT d = UpdateProgressText;
try {
this.Invoke(d, new object[] { message });
Invoke(d, new object[] { message });
} catch (ObjectDisposedException) { }
} else ProgressLabel.Text = message;
}
Expand All @@ -185,18 +212,15 @@ private bool PromptCancelDownload() {
DialogResult res = MessageBox.Show("There is a download in progress. Are you sure you want to cancel?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (res == DialogResult.Yes) {
dlThread.Abort();
try { File.Delete(filepath); } catch (Exception) { };
try { File.Delete(currentFilepath); } catch (Exception) { };
Downloading = false;
Program.Launcher.UpdateStatus("Download cancelled.");
return true;
}
return false;
}

private static void RecursiveCopy(string SourceDirectory, string DestinationDirectory) {
RecursiveCopy(SourceDirectory, DestinationDirectory, true);
}
private static void RecursiveCopy(string SourceDirectory, string DestinationDirectory, bool overwriteFile) {
private static void RecursiveCopy(string SourceDirectory, string DestinationDirectory, bool overwriteFile = true) {
if (!Directory.Exists(DestinationDirectory)) Directory.CreateDirectory(DestinationDirectory);
foreach (string f in Directory.GetFiles(SourceDirectory)) {
if (overwriteFile || !File.Exists(DestinationDirectory + "\\" + f.Split('\\').Last())) {
Expand Down
6 changes: 4 additions & 2 deletions Apex Launcher/Forms/ErrorCatcher.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 3e20087

Please sign in to comment.