Skip to content

Commit

Permalink
Merge pull request #14 from decimo3/updater
Browse files Browse the repository at this point in the history
Updater system
  • Loading branch information
decimo3 authored Mar 24, 2024
2 parents 8952bb6 + 0093dcc commit ac7e815
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 1 deletion.
23 changes: 23 additions & 0 deletions Handles/HandleCommand.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
namespace telbot.handle;
using telbot.Helpers;
using telbot.models;
public static class Command
{
Expand Down Expand Up @@ -66,8 +67,30 @@ public async static Task HandleCommand(HandleMessage bot, UsersModel user, Reque
var dias = prazo - DateTime.Today;
info.Append($"*Expiração:* {prazo.ToString("dd/MM/yyyy")} ({(int)dias.TotalDays} dias)\n");
}
info.Append($"Versão: {Updater.CurrentVersion(cfg).ToString("yyyyMMdd")}");
await bot.sendTextMesssageWraper(user.id, info.ToString());
break;
case "/update":
if(user.has_privilege != UsersModel.userLevel.administrador)
{
await bot.sendTextMesssageWraper(user.id, "Somente administradores podem usar esse comando");
break;
}
var current_version = Updater.CurrentVersion(cfg);
await bot.sendTextMesssageWraper(user.id, $"Versão atual do sistema chatbot: {current_version.ToString("yyyyMMdd")}");
await bot.sendTextMesssageWraper(user.id, "Verificando se há novas versões do sistema chatbot...");
var updates_list = Updater.ListUpdates(cfg);
var update_version = Updater.HasUpdate(updates_list, current_version);
if(update_version == null)
{
await bot.sendTextMesssageWraper(user.id, "A versão atual já é a versão mais recente!");
}
else
{
await bot.sendTextMesssageWraper(user.id, $"Nova versão {update_version} do sistema chatbot encontrada!");
Updater.Restart(cfg);
}
break;
}
return;
}
Expand Down
3 changes: 3 additions & 0 deletions Helpers/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public class Configuration
public readonly int ESPERA = 60_000;
public readonly string LOCKFILE = "sap.lock";
public readonly int VENCIMENTOS = 0;
public readonly string UPDATE_PATH = @"\\localhost\Shared\chatbot";
public readonly string TEMP_FOLDER = String.Empty;
public Configuration(string[] args)
{
LICENCE = System.Environment.GetEnvironmentVariable("BOT_LICENCE") ??
Expand All @@ -35,6 +37,7 @@ public Configuration(string[] args)
if(CURRENT_PC != AUTHORIZATION.allowed_pc) throw new InvalidOperationException("A licença de uso não permite o uso em outra máquina!");

CURRENT_PATH = System.IO.Directory.GetCurrentDirectory();
TEMP_FOLDER = CURRENT_PATH + @"\tmp\";
SAP_SCRIPT = CURRENT_PATH + @"\sap.exe";
IMG_SCRIPT = CURRENT_PATH + @"\img.exe";

Expand Down
113 changes: 113 additions & 0 deletions Helpers/Updater.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
namespace telbot.Helpers;
public static class Updater
{
public static void Update(Configuration cfg)
{
Console.WriteLine($"< {DateTime.Now} Manager: Verificando se há novas versões do sistema chatbot...");
if(!System.IO.Directory.Exists(cfg.UPDATE_PATH))
throw new DirectoryNotFoundException();
if(!System.IO.Directory.Exists(cfg.TEMP_FOLDER))
throw new DirectoryNotFoundException();
var version = CurrentVersion(cfg);
var updates = ListUpdates(cfg);
var update = HasUpdate(updates, version);
if(update != null)
{
try
{
ClearTemp(cfg);
Download(cfg, update);
Unzip(cfg);
Replace(cfg);
ClearTemp(cfg);
Restart(cfg);
}
catch (Exception erro)
{
Temporary.ConsoleWriteError($"< {DateTime.Now} Manager: Erro ao tentar atualizar o sistema chatbot!");
if(cfg.IS_DEVELOPMENT)
{
Temporary.ConsoleWriteError(erro.Message);
Temporary.ConsoleWriteError(erro.StackTrace!);
}
}
}
}
public static DateTime CurrentVersion(Configuration cfg)
{
var VersionFilepath = @"./version";
if(!System.IO.File.Exists(VersionFilepath))
throw new FileNotFoundException();
var version = System.IO.File.ReadAllText(VersionFilepath);
version = version.Replace(Environment.NewLine, "");
var version_date = DateTime.ParseExact(version, "yyyyMMdd", null);
Console.WriteLine($"< {DateTime.Now} Manager: Versão atual do sistema chatbot: {version_date.ToString("yyyyMMdd")}");
return version_date;
}
public static List<DateTime> ListUpdates(Configuration cfg)
{
var updates = System.IO.Directory.GetFiles(cfg.UPDATE_PATH);
var files_without_path = updates.Select(file => { return System.IO.Path.GetFileNameWithoutExtension(file); });
var updates_date = files_without_path.Select(update => DateTime.ParseExact(update, "yyyyMMdd", null)).ToList();
updates_date.Sort();
return updates_date;
}
public static String? HasUpdate(List<DateTime> updates, DateTime current)
{
var update = updates.FirstOrDefault(update => update > current);
if(update == default(DateTime)) return null;
var update_string = update.ToString("yyyyMMdd");
if(update_string != null)
Console.WriteLine($"< {DateTime.Now} Manager: Nova versão {update_string} do sistema chatbot encontrada!");
else
Console.WriteLine($"< {DateTime.Now} Manager: A versão atual {current.ToString("yyyyMMdd")} já é a versão mais recente!");
return update_string;
}
public static void ClearTemp(Configuration cfg)
{
var files = System.IO.Directory.GetFiles(cfg.TEMP_FOLDER);
foreach (var file in files)
{
System.IO.File.Delete(file);
}
}
public static void Download(Configuration cfg, String update)
{
var update_file = update + ".zip";
var update_filepath = System.IO.Path.Combine(cfg.UPDATE_PATH, update_file);
var update_destpath = System.IO.Path.Combine(cfg.TEMP_FOLDER, "update.zip");
System.IO.File.Copy(update_filepath, update_destpath);
}
public static void Unzip(Configuration cfg)
{
var update_filepath = System.IO.Path.Combine(cfg.TEMP_FOLDER, "update.zip");
System.IO.Compression.ZipFile.ExtractToDirectory(update_filepath, cfg.TEMP_FOLDER);
System.IO.File.Delete(update_filepath);
}
public static void Replace(Configuration cfg)
{
Console.WriteLine($"< {DateTime.Now} Manager: Atualizando o sistema chatbot, por favor aguarde...");
var files = System.IO.Directory.GetFiles(cfg.TEMP_FOLDER).Select(file => { return System.IO.Path.GetFileName(file); });
foreach (var file in files)
{
if(file == "sap.conf") continue;
if(file == "telbot.exe") continue;
if(file == "database.db") continue;
var new_file = System.IO.Path.Combine(cfg.TEMP_FOLDER, file);
var old_file = System.IO.Path.Combine(cfg.CURRENT_PATH, file);
System.IO.File.Copy(new_file, old_file, true);
}
var new_version = System.IO.Path.Combine(cfg.TEMP_FOLDER, "telbot.exe");
var current_filepath = System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName;
var temporary_filepath = current_filepath + ".old";
System.IO.File.Move(current_filepath, temporary_filepath);
System.IO.File.Copy(new_version, current_filepath, true);
}
public static void Restart(Configuration cfg)
{
Console.WriteLine($"< {DateTime.Now} Manager: Sistema chatbot atualizado com sucesso! Reiniciando...");
var executable = System.IO.Path.Combine(cfg.CURRENT_PATH, "telbot.exe");
System.Diagnostics.Process.Start(executable);
System.Environment.Exit(0);
}
}
4 changes: 3 additions & 1 deletion Startup.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Threading;
using dotenv.net;
namespace telbot;
class Startup
Expand All @@ -13,6 +12,9 @@ public static void Main(string[] args)
if(args.Contains("--em-desenvolvimento")) DotEnv.Load();
if(System.Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") == "Development") DotEnv.Load();
var config = new Configuration(args);
if(File.Exists($"{config.CURRENT_PATH}\\telbot.exe.old"))
File.Delete($"{config.CURRENT_PATH}\\telbot.exe.old");
telbot.Helpers.Updater.Update(config);
Database.configurarBanco(config);
if(File.Exists($"{config.CURRENT_PATH}\\{config.LOCKFILE}"))
File.Delete($"{config.CURRENT_PATH}\\{config.LOCKFILE}");
Expand Down
1 change: 1 addition & 0 deletions telbot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<PackageReference Include="System.Management" Version="7.0.2" />
<PackageReference Include="Telegram.Bot" Version="18.0.0" />
<SupportedPlatform Include="Windows" />
<None Include="version" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>
1 change: 1 addition & 0 deletions version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
20240324

0 comments on commit ac7e815

Please sign in to comment.