Skip to content
This repository has been archived by the owner on Nov 1, 2024. It is now read-only.

Commit

Permalink
Fixed the updater to use github releases.
Browse files Browse the repository at this point in the history
This allows the removal of compiled exe to the git repo
It also cleans up older releases, so the upgrades continue to work.

resolves #5
  • Loading branch information
sir-wilhelm committed Feb 13, 2020
1 parent 2d7065e commit ba128f8
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 101 deletions.
137 changes: 43 additions & 94 deletions SmartHunter/Core/Helpers/Updater.cs
Original file line number Diff line number Diff line change
@@ -1,126 +1,75 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SmartHunter.Game.Helpers;

namespace SmartHunter.Core.Helpers
{
public class Updater
{
private readonly List<UpdateNode> _needUpdates = new List<UpdateNode>();
private readonly string _apiEndpoint = "https://api.github.com/repos/gabrielefilipp/SmartHunter/commits?path=";
private readonly string _apiRaw = "https://github.com/gabrielefilipp/SmartHunter/raw";
private readonly string _dummyUserAgent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
private readonly string _apiEndpoint = "https://api.github.com/repos/sir-wilhelm/SmartHunter/releases/latest";
private readonly string _userAgent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

public bool CheckForUpdates(bool forceCheck = false)
public bool CheckForUpdates()
{
if (_needUpdates.Count == 0 || forceCheck == true)
try
{
try
{
using var client = new WebClient();
using var stream = client.OpenRead("http://google.com/generate_204");// check connection (maybe pointless?)
var branch = "master";
//var files = new string[5] { "SmartHunter/Game/Config/MemoryConfig.cs", "SmartHunter/Game/Config/PlayerDataConfig.cs", "SmartHunter/Game/Config/MonsterDataConfig.cs", "SmartHunter/Game/Config/LocalizationConfig.cs", "SmartHunter/bin/Debug/SmartHunter.exe" };

UpdateNode[] nodes = new UpdateNode[5] { new UpdateNode("", "SmartHunter/Game/Config/MemoryConfig.cs", "Memory.json", "", false), new UpdateNode("", "SmartHunter/Game/Config/PlayerDataConfig.cs", "PlayerData.json", "", false), new UpdateNode("", "SmartHunter/Game/Config/MonsterDataConfig.cs", "MonsterData.json", "", false), new UpdateNode("", "SmartHunter/Game/Config/LocalizationConfig.cs", "en-US.json", "", false), new UpdateNode("", "SmartHunter/bin/Debug/SmartHunter.exe", "SmartHunter.exe", "", true) };

foreach (UpdateNode node in nodes)
{
string apiUrl = $"{_apiEndpoint}{node.FilePath}";
client.Dispose();
client.Headers["User-Agent"] = _dummyUserAgent;

string apiResponseStr = client.DownloadString(apiUrl);
JArray json = JArray.Parse(apiResponseStr);
if (json.Count > 0)
{
JObject lastCommit = (JObject)json[0];
string hash = (string)lastCommit["sha"];
if (!ConfigHelper.Versions.Values.GetType().GetField(Path.GetFileNameWithoutExtension(node.FilePath)).GetValue(ConfigHelper.Versions.Values).Equals(hash))
{
Log.WriteLine($"Found a new version of '{Path.GetFileName(node.FileName)}'");
node.Hash = hash;
if (node.NeedDownload)
{
node.DownloadUrl = $"{_apiRaw}/{branch}/{node.FilePath}";
}
_needUpdates.Add(node);
}
}
}
}
catch
{
Log.WriteLine($"An error has occured while searching for updates... Resuming the normal flow of the application!");
return false;
}
var latestRelease = GetLatestRelease();
return new Version(latestRelease.tag_name) > Assembly.GetExecutingAssembly().GetName().Version;
}
catch (Exception e)
{
Log.WriteLine($"An error has occured while searching for updates:{Environment.NewLine}{e}");
Log.WriteLine("Resuming the normal flow of the application.");
return false;
}
return _needUpdates.Count > 0;
}

private LatestRelease GetLatestRelease()
{
var request = WebRequest.CreateHttp(_apiEndpoint);
request.ContentType = "application/json";
request.UserAgent = _userAgent;
using var stream = request.GetResponse().GetResponseStream();
using var reader = new StreamReader(stream);
var latestReleaseAsJson = reader.ReadToEnd();
return JsonConvert.DeserializeObject<LatestRelease>(latestReleaseAsJson);
}

public bool DownloadUpdates()
{
try
{
var latestRelease = GetLatestRelease();

using var client = new WebClient();
while (_needUpdates.Count > 0)
{
UpdateNode node = _needUpdates.First();
string hash = node.Hash;
string filePath = node.FilePath;
string fileName = node.FileName;
string fileNamePath = Path.GetFileName(filePath);
string fileNamePathWithNoExtension = Path.GetFileNameWithoutExtension(filePath);
if (node.NeedDownload)
{
string url = node.DownloadUrl;
Log.WriteLine($"Downloading file '{fileNamePath}'");
client.Dispose();
client.Headers["User-Agent"] = _dummyUserAgent;
if (Path.GetExtension(fileNamePath).Equals(".exe"))
{
client.DownloadFile(url, $"{fileNamePathWithNoExtension}_NEW.exe");
}
else
{
client.DownloadFile(url, fileNamePath);
}
}
else
{
Log.WriteLine($"Deleting file '{fileName}'");
File.Delete(fileName);
}
ConfigHelper.Versions.Values.GetType().GetField(fileNamePathWithNoExtension).SetValue(ConfigHelper.Versions.Values, hash);
ConfigHelper.Versions.Save();
_needUpdates.Remove(node);
}
var releaseZip = latestRelease.assets[0];
Log.WriteLine("Deleting older update.");
File.Delete(releaseZip.name);
client.DownloadFile(releaseZip.browser_download_url, releaseZip.name);
return true;
}
catch
catch (Exception e)
{
Log.WriteLine($"An error has occured while downloading update:{Environment.NewLine}{e}");
return false;
}
return true;
}

private class UpdateNode // TODO: Add a variable to contain a function pointer to execute a specific action if that Node needs to be updated
internal class LatestRelease
{
public string Hash { get; set; }
public string FilePath { get; }
public string FileName { get; set; }
public string DownloadUrl { get; set; }
public bool NeedDownload { get; }
public UpdateNode(string h, string path, string name, string url, bool download = false)
{
Hash = h;
FilePath = path;
FileName = name;
DownloadUrl = url;
NeedDownload = download;
}
public string tag_name { get; set; }
public Asset[] assets { get; set; }
}
internal class Asset
{
public string name { get; set; }
public string browser_download_url { get; set; }
}
}
}
29 changes: 22 additions & 7 deletions SmartHunter/Core/MemoryUpdater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Windows;
Expand Down Expand Up @@ -127,15 +128,29 @@ void CreateStateMachine()
() => true,
() =>
{
Log.WriteLine("Restarting Application!");
string update = ".\\SmartHunter_NEW.exe";
string exec = Assembly.GetEntryAssembly()?.Location;
if (File.Exists(update) && exec != null && File.Exists(exec))
Log.WriteLine("Deleting older updates");
var currentDirectory = Directory.GetCurrentDirectory();
var oldFiles = Directory.GetFiles(currentDirectory, "OLD_*", SearchOption.TopDirectoryOnly);
foreach (var oldFile in oldFiles)
{
File.Move(exec, "SmartHunter_OLD.exe");
File.Move(update, "SmartHunter.exe");
Process.Start("SmartHunter.exe");
File.Delete(oldFile);
}

Log.WriteLine("Renaming files that will be replaced");
using var archive = ZipFile.OpenRead("SmartHunter.zip");
foreach (var entry in archive.Entries)
{
if (File.Exists(entry.Name))
{
File.Move(entry.Name, $"OLD_{entry.Name}");
}
}

Log.WriteLine("Extracting new files.");
archive.ExtractToDirectory(currentDirectory);

Log.WriteLine("Update complete, Starting new SmartHunter, and exiting");
Process.Start("SmartHunter.exe");
Environment.Exit(1);
})
}));
Expand Down
1 change: 1 addition & 0 deletions SmartHunter/SmartHunter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
</Target>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="System.IO.Compression" Version="4.3.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
Expand Down

0 comments on commit ba128f8

Please sign in to comment.