Skip to content

Commit

Permalink
first working version
Browse files Browse the repository at this point in the history
  • Loading branch information
Kalle Minkner committed Nov 8, 2024
1 parent d14c502 commit 915d1ab
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 8 deletions.
4 changes: 0 additions & 4 deletions src/UpdateManager+Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ public void CommandUpdatePlugins(CCSPlayerController player, CommandInfo command
{
// update plugin list
getPluginList();
// initialize configuration
LoadConfig();
UpdateConfig();
SaveConfig();
// check for updates
checkForUpdates();
}
Expand Down
85 changes: 83 additions & 2 deletions src/UpdateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@
using CounterStrikeSharp.API.Core;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using System.IO.Compression;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace UpdateManager
{
public partial class UpdateManager : BasePlugin
{
public override string ModuleName => "Update Manager";
public override string ModuleAuthor => "Jon-Mailes Graeffe <[email protected]> / Kalle <[email protected]>";
public override string ModuleVersion => "0.0.1";
public override string ModuleVersion => "0.1.0";

private string _pluginPath = "";
private List<Tuple<string, string, string>> _plugins = new();
Expand Down Expand Up @@ -53,6 +56,7 @@ private void OnServerHibernationUpdate(bool isHibernating)

private void getPluginList()
{
_plugins.Clear();
var directories = Directory.GetDirectories(_pluginPath);
foreach (var dir in directories)
{
Expand Down Expand Up @@ -87,13 +91,90 @@ private void checkForUpdates()
var pluginConfig = Config.Plugins[pluginName];
if (pluginConfig == null || !pluginConfig.Enabled) continue;
// check github api /repos/{owner}/{repo}/releases/latest
try {
var client = new HttpClient();
client.DefaultRequestHeaders.Add("User-Agent", "CounterStrikeSharp");
if (!string.IsNullOrEmpty(pluginConfig.GithubToken))
client.DefaultRequestHeaders.Add("Authorization", $"token {pluginConfig.GithubToken}");
var repoPath = new Uri(pluginRepoURL).AbsolutePath.Trim('/');
var response = client.GetAsync($"https://api.github.com/repos/{repoPath}/releases/latest").Result;
Console.WriteLine(response);
// check if response is successful
if (!response.IsSuccessStatusCode) {
Console.WriteLine(Localizer["update.error"].Value
.Replace("{error}", response.ReasonPhrase));
continue;
}
// parse response
var responseString = response.Content.ReadAsStringAsync().Result;
// get download url for latest .zip
var release = JsonSerializer.Deserialize<Dictionary<string, object>>(responseString);
if (release == null)
{
Console.WriteLine(Localizer["update.error"].Value
.Replace("{pluginName}", pluginName)
.Replace("{error}", "Release data not found."));
continue;
}
if (!release.TryGetValue("tag_name", out var tagName))
{
Console.WriteLine(Localizer["update.error"].Value
.Replace("{pluginName}", pluginName)
.Replace("{error}", "Tag name not found in release data."));
continue;
}
var latestVersion = tagName.ToString();
if (latestVersion == pluginVersion)
{
Console.WriteLine(Localizer["update.notfound"].Value
.Replace("{pluginName}", pluginName)
.Replace("{pluginVersion}", pluginVersion));
continue;
}
Console.WriteLine(Localizer["update.available"].Value
.Replace("{pluginName}", pluginName)
.Replace("{pluginVersion}", pluginVersion)
.Replace("{latestVersion}", latestVersion));
// download and update plugin
if (!release.TryGetValue("assets", out var assets) || assets == null)
{
Console.WriteLine(Localizer["update.error"].Value
.Replace("{pluginName}", pluginName)
.Replace("{error}", "Assets not found in release data."));
continue;
}
var assetList = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(assets?.ToString() ?? string.Empty);
var zipAsset = assetList?.FirstOrDefault(a =>
{
if (a == null) return false;
return a.TryGetValue("name", out var name) && name?.ToString().EndsWith(".zip") == true;

Check warning on line 149 in src/UpdateManager.cs

View workflow job for this annotation

GitHub Actions / create-release

Dereference of a possibly null reference.
});
if (zipAsset == null || !zipAsset.TryGetValue("browser_download_url", out var browserDownloadUrl))
{
Console.WriteLine(Localizer["update.error"].Value
.Replace("{pluginName}", pluginName)
.Replace("{error}", "Download URL for .zip file not found in assets."));
continue;
}
var downloadURL = browserDownloadUrl.ToString();
var downloadPath = Path.Combine(_pluginPath, $"{pluginName}.zip");
var downloadStream = client.GetStreamAsync(downloadURL).Result;
using (var fileStream = File.Create(downloadPath))
{
downloadStream.CopyTo(fileStream);
}
// extract zip
ZipFile.ExtractToDirectory(downloadPath, _pluginPath, true);
// remove zip
File.Delete(downloadPath);
Console.WriteLine(Localizer["update.success"].Value
.Replace("{pluginName}", pluginName)
.Replace("{pluginVersion}", pluginVersion)
.Replace("{latestVersion}", latestVersion));
} catch (Exception e) {
Console.WriteLine(Localizer["update.error"].Value
.Replace("{pluginName}", pluginName)
.Replace("{error}", e.Message));
}
}
}
}
Expand Down
6 changes: 5 additions & 1 deletion src/lang/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@
"core.hotreload": "[UpdateManager] Neu geladen!",
"core.unload": "[UpdateManager] Plugin entladen!",
"config.loaded": "[UpdateManager] Konfiguration geladen!",
"plugin.found": "[UpdateManager] Plugin gefunden: {pluginName} v{pluginVersion}"
"plugin.found": "[UpdateManager] Plugin gefunden: {pluginName} v{pluginVersion}",
"update.error": "[UpdateManager] Fehler beim Aktualisieren des Plugins {pluginName}: {error}",
"update.available": "[UpdateManager] Neue Version verfügbar: {pluginName} v{latestVersion} (aktuell: v{pluginVersion})",
"update.notfound": "[UpdateManager] {pluginName} v{pluginVersion} ist bereits die neueste Version",
"update.success": "[UpdateManager] Plugin {pluginName} aktualisiert von v{pluginVersion} auf v{latestVersion}"
}
6 changes: 5 additions & 1 deletion src/lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@
"core.hotreload": "[UpdateManager] Hot-Reloaded Plugin!",
"core.unload": "[UpdateManager] Unloaded Plugin!",
"config.loaded": "[UpdateManager] Loaded configuration!",
"plugin.found": "[UpdateManager] Found plugin: {pluginName} v{pluginVersion}"
"plugin.found": "[UpdateManager] Found plugin: {pluginName} v{pluginVersion}",
"update.error": "[UpdateManager] Error while updating plugin {pluginName}: {error}",
"update.available": "[UpdateManager] New version available: {pluginName} v{latestVersion} (current: v{pluginVersion})",
"update.notfound": "[UpdateManager] {pluginName} v{pluginVersion} is already the newest version",
"update.success": "[UpdateManager] Plugin {pluginName} updated from v{pluginVersion} to v{latestVersion}"
}

0 comments on commit 915d1ab

Please sign in to comment.