Split UpToolLib into v1 (basically an interface over XElements with rudementary parsing) and v2 (more object-oriented, less hacky API, will allow easier migration to a more suited information backend) and start work on a new eto-based UI (not functional currently)

This commit is contained in:
JFronny 2021-02-08 19:00:46 +01:00
parent ba106c1783
commit 6af8eba6c6
65 changed files with 1353 additions and 494 deletions

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="RIDER_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$/../.." />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -17,6 +17,7 @@
{
components.Dispose();
}
_lib.Dispose();
base.Dispose(disposing);
}

View File

@ -11,7 +11,8 @@ using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Win32;
using UpToolLib;
using UpToolLib.Tool;
using UpToolLib.v1.Tool;
using UpToolLib.v2;
namespace Installer
{
@ -20,16 +21,17 @@ namespace Installer
private const string AppName = "UpTool2";
private readonly RegistryKey _rkApp;
private string _log = "";
private UpToolLibMain _lib;
public InstallerForm()
{
ExternalFunctionalityManager.Init(new UtLibFunctionsGui(Log));
_lib = new UpToolLibMain(new UtLibFunctionsGui(Log));
InitializeComponent();
Step(0, "Initialized");
_log = _log.TrimStart(Environment.NewLine.ToCharArray());
_rkApp = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
pathBox.Checked = !File.Exists(PathTool.InfoXml) ||
Path.Content.Contains(Path.GetName(PathTool.GetRelative("Install")));
pathBox.Checked = !File.Exists(_lib.V1.PathTool.InfoXml) ||
Path.Content.Contains(Path.GetName(_lib.V1.PathTool.GetRelative("Install")));
startupBox.Checked = pathBox.Checked && _rkApp.GetValue(AppName) != null;
updateAppsBox.Checked = pathBox.Checked && startupBox.Checked &&
(string) _rkApp.GetValue(AppName) == "uptool dist-upgrade";
@ -41,7 +43,7 @@ namespace Installer
try
{
progress.Visible = true;
WebClient client = new WebClient();
WebClient client = new();
Step(1, "Downloading metadata");
XElement meta = XDocument
.Load("https://gitlab.com/JFronny/UpTool2/-/jobs/artifacts/master/raw/meta.xml?job=uptool")
@ -49,7 +51,7 @@ namespace Installer
Step(2, "Downloading binary");
byte[] dl = client.DownloadData(meta.Element("File").Value);
Step(3, "Verifying integrity");
using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
using (SHA256CryptoServiceProvider sha256 = new())
{
string pkgHash = BitConverter.ToString(sha256.ComputeHash(dl)).Replace("-", string.Empty).ToUpper();
if (pkgHash != meta.Element("Hash").Value.ToUpper())
@ -59,26 +61,26 @@ Package: {pkgHash}
Online: {meta.Element("Hash").Value.ToUpper()}");
}
Step(4, "Extracting");
if (Directory.Exists(PathTool.GetRelative("Install")))
Directory.Delete(PathTool.GetRelative("Install"), true);
Directory.CreateDirectory(PathTool.GetRelative("Install"));
using (MemoryStream ms = new MemoryStream(dl))
if (Directory.Exists(_lib.V1.PathTool.GetRelative("Install")))
Directory.Delete(_lib.V1.PathTool.GetRelative("Install"), true);
Directory.CreateDirectory(_lib.V1.PathTool.GetRelative("Install"));
using (MemoryStream ms = new(dl))
{
using ZipArchive ar = new ZipArchive(ms);
ar.ExtractToDirectory(PathTool.GetRelative("Install"), true);
using ZipArchive ar = new(ms);
ar.ExtractToDirectory(_lib.V1.PathTool.GetRelative("Install"), true);
}
Step(5, "Creating shortcut");
Shortcut.Make(PathTool.GetRelative("Install", "UpTool2.exe"),
Shortcut.Make(_lib.V1.PathTool.GetRelative("Install", "UpTool2.exe"),
System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs),
"UpTool2.lnk"));
Step(6, "Preparing Repos");
XmlTool.FixXml();
RepoManagement.FetchRepos();
_lib.V1.XmlTool.FixXml();
_lib.V2.RepoManagement.FetchRepos();
if (pathBox.Checked)
{
Step(7, startupBox.Checked ? "Creating PATH & Autostart entry" : "Creating PATH entry");
if (!Path.Content.Contains(Path.GetName(PathTool.GetRelative("Install"))))
Path.Append(PathTool.GetRelative("Install"));
if (!Path.Content.Contains(Path.GetName(_lib.V1.PathTool.GetRelative("Install"))))
Path.Append(_lib.V1.PathTool.GetRelative("Install"));
if (startupBox.Checked)
_rkApp.SetValue(AppName, updateAppsBox.Checked ? "uptool dist-upgrade" : "uptool upgrade-self");
else if (_rkApp.GetValue(AppName) != null)

View File

@ -12,18 +12,10 @@ namespace Installer
[STAThread]
private static void Main()
{
try
{
MutexLock.Lock();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new InstallerForm());
}
finally
{
MutexLock.Unlock();
}
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new InstallerForm());
}
}
}

View File

@ -16,7 +16,7 @@ namespace Installer
public Tuple<bool, byte[]> Download(Uri link)
{
using WebClient cli = new WebClient();
using WebClient cli = new();
try
{
return new Tuple<bool, byte[]>(true, cli.DownloadData(link));
@ -29,10 +29,10 @@ namespace Installer
public string FetchImageB64(Uri link)
{
using WebClient client = new WebClient();
using WebClient client = new();
Image src = Image.FromStream(
client.OpenRead(link));
Bitmap dest = new Bitmap(70, 70);
Bitmap dest = new(70, 70);
dest.SetResolution(src.HorizontalResolution, src.VerticalResolution);
using (Graphics g = Graphics.FromImage(dest))
{
@ -41,12 +41,12 @@ namespace Installer
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
using ImageAttributes wrapMode = new ImageAttributes();
using ImageAttributes wrapMode = new();
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
g.DrawImage(src, new Rectangle(0, 0, 70, 70), 0, 0, src.Width, src.Height,
GraphicsUnit.Pixel, wrapMode);
}
using MemoryStream ms = new MemoryStream();
using MemoryStream ms = new();
dest.Save(ms, ImageFormat.Png);
return Convert.ToBase64String(ms.ToArray());
}

View File

@ -7,24 +7,26 @@ using System.Net;
using System.Security.Cryptography;
using System.Threading;
using UpToolLib;
using UpToolLib.Tool;
using UpToolLib.v1.Tool;
using UpToolLib.v2;
namespace Installer
{
public static class Program
{
public static bool Basic;
private static UpToolLibMain _lib;
public static int Main(string[] args)
{
Thread.Sleep(2000);
MutexLock.Lock();
try
{
Basic = args.Length > 0 && args[0].ToLower() == "--basic";
ExternalFunctionalityManager.Init(new UtLibFunctions());
RootCommand rootCommand = new RootCommand();
rootCommand.AddGlobalOption(new Option<bool>("--basic", "Use only basic console functionality. Must be the first parameter in the call"));
Command install = new Command("install", "Install UpTool")
_lib = new UpToolLibMain(new UtLibFunctions());
RootCommand rootCommand = new();
rootCommand.AddGlobalOption(new Option<bool>("--basic",
"Use only basic console functionality. Must be the first parameter in the call"));
Command install = new("install", "Install UpTool")
{
new Option<bool>(new[] {"--noPrep", "-p"}, "Doesn't initialize repos. Use with caution!")
};
@ -41,45 +43,48 @@ namespace Installer
}
finally
{
MutexLock.Unlock();
_lib?.Dispose();
}
}
private static void Install(bool noPrep)
{
WebClient client = new WebClient();
WebClient client = new();
Console.WriteLine("Downloading metadata");
UpdateCheck.Reload("https://gitlab.com/JFronny/UpTool2/-/jobs/artifacts/master/raw/meta.xml?job=uptool");
UpdateCheck check =
_lib.V2.UpdateChecker.Check(
"https://gitlab.com/JFronny/UpTool2/-/jobs/artifacts/master/raw/meta.xml?job=uptool");
PathTool pathTool = _lib.V1.PathTool;
Console.WriteLine("Downloading binary");
byte[] dl = client.DownloadData(UpdateCheck.App);
byte[] dl = client.DownloadData(check.App);
Console.WriteLine("Verifying integrity");
using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
using (SHA256CryptoServiceProvider sha256 = new())
{
string pkgHash = BitConverter.ToString(sha256.ComputeHash(dl)).Replace("-", string.Empty)
.ToUpper();
if (pkgHash != UpdateCheck.AppHash)
if (pkgHash != check.AppHash)
throw new Exception($@"The hash is not equal to the one stored in the repo:
Package: {pkgHash}
Online: {UpdateCheck.AppHash}");
Online: {check.AppHash}");
}
Console.WriteLine("Extracting");
if (Directory.Exists(PathTool.GetRelative("Install")))
if (Directory.Exists(pathTool.GetRelative("Install")))
{
foreach (string file in Directory.GetFiles(PathTool.GetRelative("Install"))) File.Delete(file);
foreach (string dir in Directory.GetDirectories(PathTool.GetRelative("Install")))
foreach (string file in Directory.GetFiles(pathTool.GetRelative("Install"))) File.Delete(file);
foreach (string dir in Directory.GetDirectories(pathTool.GetRelative("Install")))
if (Path.GetFileName(dir) != "tmp")
Directory.Delete(dir, true);
}
Directory.CreateDirectory(PathTool.GetRelative("Install"));
using (MemoryStream ms = new MemoryStream(dl))
Directory.CreateDirectory(pathTool.GetRelative("Install"));
using (MemoryStream ms = new(dl))
{
using ZipArchive ar = new ZipArchive(ms);
ar.ExtractToDirectory(PathTool.GetRelative("Install"), true);
using ZipArchive ar = new(ms);
ar.ExtractToDirectory(pathTool.GetRelative("Install"), true);
}
if (noPrep) return;
Console.WriteLine("Preparing Repos");
XmlTool.FixXml();
RepoManagement.FetchRepos();
_lib.V1.XmlTool.FixXml();
_lib.V2.RepoManagement.FetchRepos();
}
}
}

View File

@ -13,7 +13,7 @@ namespace Installer
{
public Tuple<bool, byte[]> Download(Uri link)
{
using WebClient client = new WebClient();
using WebClient client = new();
byte[] result = new byte[0];
bool finished = false;
bool success = true;
@ -41,10 +41,9 @@ namespace Installer
public string FetchImageB64(Uri link)
{
using WebClient client = new WebClient();
using WebClient client = new();
using Image image = Image.Load(client.OpenRead(link));
image.Mutate(x => x.Resize(70, 70));
using MemoryStream ms = new MemoryStream();
using MemoryStream ms = new();
image.SaveAsPng(ms);
return Convert.ToBase64String(ms.ToArray());
}

View File

@ -29,6 +29,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{0E7784
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InstallerCLI", "InstallerCLI\InstallerCLI.csproj", "{493B2CC5-29E9-4F10-A2F5-E10B9584D667}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UpToolEto", "UpToolEto\UpToolEto\UpToolEto.csproj", "{213FF69B-426E-475F-8A77-0A20EA4257C2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UpToolEto.Gtk", "UpToolEto\UpToolEto.Gtk\UpToolEto.Gtk.csproj", "{8A544AEA-3081-45C9-BED2-7E424EB287B1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UpToolEto.Wpf", "UpToolEto\UpToolEto.Wpf\UpToolEto.Wpf.csproj", "{C89EC79F-CC2B-4B8E-B4CB-D4DFD30A58AB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -59,6 +65,18 @@ Global
{493B2CC5-29E9-4F10-A2F5-E10B9584D667}.Debug|Any CPU.Build.0 = Debug|Any CPU
{493B2CC5-29E9-4F10-A2F5-E10B9584D667}.Release|Any CPU.ActiveCfg = Release|Any CPU
{493B2CC5-29E9-4F10-A2F5-E10B9584D667}.Release|Any CPU.Build.0 = Release|Any CPU
{213FF69B-426E-475F-8A77-0A20EA4257C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{213FF69B-426E-475F-8A77-0A20EA4257C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{213FF69B-426E-475F-8A77-0A20EA4257C2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{213FF69B-426E-475F-8A77-0A20EA4257C2}.Release|Any CPU.Build.0 = Release|Any CPU
{8A544AEA-3081-45C9-BED2-7E424EB287B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8A544AEA-3081-45C9-BED2-7E424EB287B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8A544AEA-3081-45C9-BED2-7E424EB287B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8A544AEA-3081-45C9-BED2-7E424EB287B1}.Release|Any CPU.Build.0 = Release|Any CPU
{C89EC79F-CC2B-4B8E-B4CB-D4DFD30A58AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C89EC79F-CC2B-4B8E-B4CB-D4DFD30A58AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C89EC79F-CC2B-4B8E-B4CB-D4DFD30A58AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C89EC79F-CC2B-4B8E-B4CB-D4DFD30A58AB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -73,5 +91,8 @@ Global
{3EC369B9-D927-4A53-BE1A-7E7006081BCE} = {3CFAB991-C12A-4B51-BC91-6965133DAF53}
{1D273392-3796-4BE9-A67F-BB402315D52D} = {EA919DFD-766B-423C-99DF-C99356592842}
{493B2CC5-29E9-4F10-A2F5-E10B9584D667} = {3CFAB991-C12A-4B51-BC91-6965133DAF53}
{213FF69B-426E-475F-8A77-0A20EA4257C2} = {EA919DFD-766B-423C-99DF-C99356592842}
{8A544AEA-3081-45C9-BED2-7E424EB287B1} = {EA919DFD-766B-423C-99DF-C99356592842}
{C89EC79F-CC2B-4B8E-B4CB-D4DFD30A58AB} = {EA919DFD-766B-423C-99DF-C99356592842}
EndGlobalSection
EndGlobal

View File

@ -6,30 +6,31 @@ using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using UpTool2.Task;
using UpToolLib;
using UpToolLib.DataStructures;
using UpToolLib.Tool;
using System.Diagnostics;
using UpToolLib.v1.Tool;
using UpToolLib.v2;
using UpToolLib.v2.TaskQueue;
namespace UpTool2
{
public sealed partial class MainForm : Form
{
private readonly HelpEventHandler _help;
private List<IAppTask> _tasks;
private List<AppTask> _tasks;
public MainForm()
{
InitializeComponent();
_tasks = new List<IAppTask>();
_tasks = new List<AppTask>();
_help = MainForm_HelpRequested;
HelpRequested += _help;
filterBox.DataSource = Enum.GetValues(typeof(Status));
if (Program.Online)
{
Program.SetSplash(8, "Fetching repositories");
RepoManagement.FetchRepos();
Program.Lib.V2.RepoManagement.FetchRepos();
}
else
{
@ -40,8 +41,8 @@ namespace UpTool2
}
Program.SetSplash(9, "Reloading data");
ReloadElements();
if (!Directory.Exists(PathTool.AppsPath))
Directory.CreateDirectory(PathTool.AppsPath);
if (!Directory.Exists(Program.Lib.V1.PathTool.AppsPath))
Directory.CreateDirectory(Program.Lib.V1.PathTool.AppsPath);
}
private void Action_install_Click(object sender, EventArgs e)
@ -54,7 +55,7 @@ namespace UpTool2
}
else
{
_tasks.Add(new InstallTask(tmp, ReloadElements));
_tasks.Add(Program.Lib.V2.TaskFactory.CreateInstall(tmp, ReloadElements));
action_install.BackColor = Color.Green;
}
UpdateChangesLabel();
@ -70,7 +71,7 @@ namespace UpTool2
}
else
{
_tasks.Add(new RemoveTask(tmp, ReloadElements));
_tasks.Add(Program.Lib.V2.TaskFactory.CreateRemove(tmp, ReloadElements));
action_remove.BackColor = Color.Green;
}
UpdateChangesLabel();
@ -81,7 +82,7 @@ namespace UpTool2
if (searchPackageDialog.ShowDialog() != DialogResult.OK)
return;
if (!_tasks.Any(s => s is UploadTask t && t.ZipFile == searchPackageDialog.FileName))
_tasks.Add(new UploadTask(searchPackageDialog.FileName, AppNameDialog.Show(), ReloadElements));
_tasks.Add(Program.Lib.V2.TaskFactory.CreateUpload(searchPackageDialog.FileName, AppNameDialog.Show(), ReloadElements));
UpdateChangesLabel();
}
@ -95,7 +96,7 @@ namespace UpTool2
}
else
{
_tasks.Add(new UpdateTask(tmp, ReloadElements));
_tasks.Add(Program.Lib.V2.TaskFactory.CreateUpdate(tmp, ReloadElements));
action_update.BackColor = Color.Green;
}
UpdateChangesLabel();
@ -110,7 +111,7 @@ namespace UpTool2
infoPanel_Description.Invalidate();
int f = sidebarPanel.Controls.Count;
for (int i = 0; i < f; i++) sidebarPanel.Controls[0].Dispose();
GlobalVariables.Apps.Clear();
Program.Lib.V1.Apps.Clear();
//add
toolTip.SetToolTip(controls_settings, "Settings");
toolTip.SetToolTip(controls_reload, "Refresh repositories");
@ -120,9 +121,9 @@ namespace UpTool2
toolTip.SetToolTip(action_remove, "Remove");
toolTip.SetToolTip(action_update, "Update");
toolTip.SetToolTip(action_run, "Run");
RepoManagement.GetReposFromDisk();
Program.Lib.V2.RepoManagement.GetReposFromDisk();
int availableUpdates = 0;
foreach (App app in GlobalVariables.Apps.Values)
foreach (App app in Program.Lib.V1.Apps.Values)
{
Panel sidebarIcon = new Panel
{
@ -180,7 +181,7 @@ namespace UpTool2
{
try
{
AppExtras.RunApp((App) action_run.Tag);
Program.Lib.V1.AppExtras.RunApp((App) action_run.Tag);
}
catch (Exception e1)
{
@ -195,7 +196,7 @@ namespace UpTool2
{
new Thread(() =>
{
RepoManagement.FetchRepos();
Program.Lib.V2.RepoManagement.FetchRepos();
Invoke((Action) (() =>
{
ReloadElements();
@ -229,7 +230,7 @@ namespace UpTool2
string tmpFile = Path.GetTempFileName();
File.WriteAllText(tmpFile,
string.Join("\r\n\r\n",
GlobalVariables.Apps.Values.Select(app => app.ToString()).Concat(new[]
Program.Lib.V1.Apps.Values.Select(app => app.ToString()).Concat(new[]
{
$"Assembly version: {Assembly.GetExecutingAssembly().GetName().Version}"
}).ToArray()));
@ -241,7 +242,7 @@ namespace UpTool2
}
else
{
App[] apps = AppExtras.FindApps(searchBox.Text);
App[] apps = Program.Lib.V1.AppExtras.FindApps(searchBox.Text);
Enum.TryParse(filterBox.SelectedValue.ToString(), out Status status);
for (int i = 0; i < sidebarPanel.Controls.Count; i++)
{
@ -315,7 +316,7 @@ Build Date: {buildTime:dd.MM.yyyy}", "UpTool2");
{
progressBar1.Maximum = _tasks.Count;
progressBar1.Value = 0;
foreach (IAppTask task in _tasks)
foreach (AppTask task in _tasks)
{
task.Run();
progressBar1.PerformStep();

View File

@ -9,7 +9,8 @@ using System.Windows.Forms;
using System.Xml;
using UpTool2.Tool;
using UpToolLib;
using UpToolLib.Tool;
using UpToolLib.v1.Tool;
using UpToolLib.v2;
namespace UpTool2
{
@ -19,6 +20,7 @@ namespace UpTool2
private static int _splashProgress;
private static string? _splashMessage;
public static bool Online;
public static UpToolLibMain Lib;
[STAThread]
private static void Main(string[] args)
@ -29,7 +31,7 @@ namespace UpTool2
Splash.Show();
try
{
MutexLock.Lock();
Lib = new UpToolLibMain(new UtLibFunctions());
}
catch (MutexLockLockedException)
{
@ -43,23 +45,22 @@ namespace UpTool2
try
{
#endif
ExternalFunctionalityManager.Init(new UtLibFunctions());
SetSplash(1, "Initializing paths");
if (!Directory.Exists(PathTool.Dir))
Directory.CreateDirectory(PathTool.Dir);
if (!Directory.Exists(Lib.V1.PathTool.Dir))
Directory.CreateDirectory(Lib.V1.PathTool.Dir);
FixXml();
SetSplash(2, "Performing checks");
try
{
UpToolLib.UpdateCheck.Reload();
Lib.V2.UpdateChecker.Check();
Online = true;
}
catch
{
Online = false;
}
if (!Directory.Exists(PathTool.GetRelative("Apps")))
Directory.CreateDirectory(PathTool.GetRelative("Apps"));
if (!Directory.Exists(Lib.V1.PathTool.GetRelative("Apps")))
Directory.CreateDirectory(Lib.V1.PathTool.GetRelative("Apps"));
if (!Online)
SetSplash(7, "Opening");
if (!Online || UpdateCheck())
@ -80,7 +81,7 @@ namespace UpTool2
}
finally
{
MutexLock.Unlock();
Lib.Dispose();
}
#endif
}
@ -157,28 +158,29 @@ namespace UpTool2
{
try
{
XmlTool.FixXml();
Lib.V1.XmlTool.FixXml();
}
catch (XmlException)
{
if (throwOnError) throw;
MessageBox.Show("Something went wrong while trying to parse XML. Retrying...");
File.Delete(PathTool.InfoXml);
File.Delete(Lib.V1.PathTool.InfoXml);
FixXml();
}
}
private static bool UpdateCheck()
{
UpdateCheck check = Lib.V2.UpdateChecker.Check();
SetSplash(3, "Comparing online version");
if (Assembly.GetExecutingAssembly().GetName().Version >= UpToolLib.UpdateCheck.OnlineVersion)
if (Assembly.GetExecutingAssembly().GetName().Version >= check.OnlineVersion)
{
SetSplash(7, "Opening");
return true;
}
byte[] dl;
SetSplash(4, "Downloading latest");
using (DownloadDialog dlg = new DownloadDialog(UpToolLib.UpdateCheck.Installer.AbsoluteUri))
using (DownloadDialog dlg = new DownloadDialog(check.Installer.AbsoluteUri))
{
if (dlg.ShowDialog() != DialogResult.OK)
throw new Exception("Failed to update");
@ -188,27 +190,27 @@ namespace UpTool2
using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
{
string pkgHash = BitConverter.ToString(sha256.ComputeHash(dl)).Replace("-", string.Empty).ToUpper();
if (pkgHash != UpToolLib.UpdateCheck.InstallerHash)
if (pkgHash != check.InstallerHash)
throw new Exception(
$"The hash is not equal to the one stored in the repo:\r\nPackage: {pkgHash}\r\nOnline: {UpToolLib.UpdateCheck.InstallerHash}");
$"The hash is not equal to the one stored in the repo:\r\nPackage: {pkgHash}\r\nOnline: {check.InstallerHash}");
}
SetSplash(9, "Installing");
if (Directory.Exists(PathTool.GetRelative("Install", "tmp")))
Directory.Delete(PathTool.GetRelative("Install", "tmp"), true);
Directory.CreateDirectory(PathTool.GetRelative("Install", "tmp"));
if (Directory.Exists(Lib.V1.PathTool.GetRelative("Install", "tmp")))
Directory.Delete(Lib.V1.PathTool.GetRelative("Install", "tmp"), true);
Directory.CreateDirectory(Lib.V1.PathTool.GetRelative("Install", "tmp"));
using (MemoryStream ms = new MemoryStream(dl))
{
using ZipArchive ar = new ZipArchive(ms);
ar.ExtractToDirectory(PathTool.GetRelative("Install", "tmp"), true);
ar.ExtractToDirectory(Lib.V1.PathTool.GetRelative("Install", "tmp"), true);
}
Splash.Hide();
Process.Start(new ProcessStartInfo
{
FileName = PathTool.GetRelative("Install", "tmp", "Installer.exe"),
FileName = Lib.V1.PathTool.GetRelative("Install", "tmp", "Installer.exe"),
Arguments = "i -p",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = PathTool.GetRelative("Install")
WorkingDirectory = Lib.V1.PathTool.GetRelative("Install")
});
SetSplash(7, "Installing");
return false;

View File

@ -1,35 +1,27 @@
using System.Windows.Forms;
using System.Xml.Linq;
using UpToolLib.Tool;
using System.Collections.Generic;
using System.Windows.Forms;
using UpToolLib.DataStructures;
namespace UpTool2
{
public partial class SettingsForms : Form
{
private readonly XDocument _doc;
private readonly XElement _repos;
private readonly List<Repo> _repos = new List<Repo>();
public SettingsForms()
{
InitializeComponent();
Program.FixXml();
_doc = XDocument.Load(PathTool.InfoXml);
_repos = _doc.Element("meta").Element("Repos");
_repos.AddRange(Program.Lib.V2.RepoManagement.GetRepos());
sourceGrid.Columns.Clear();
sourceGrid.Columns.Add("name", "Name");
sourceGrid.Columns.Add("link", "Link");
foreach (XElement repo in _repos.Elements("Repo"))
sourceGrid.Rows.Add(repo.Element("Name").Value, repo.Element("Link").Value);
foreach (Repo repo in _repos)
sourceGrid.Rows.Add(repo.Name, repo.Url);
}
private void SettingsForms_FormClosing(object sender, FormClosingEventArgs e)
{
_repos.RemoveNodes();
for (int y = 0; y < sourceGrid.Rows.Count; y++)
if (y + 1 < sourceGrid.Rows.Count)
_repos.Add(new XElement("Repo", new XElement("Name", (string) sourceGrid.Rows[y].Cells[0].Value),
new XElement("Link", (string) sourceGrid.Rows[y].Cells[1].Value)));
_doc.Save(PathTool.InfoXml);
Program.Lib.V2.RepoManagement.Save(_repos);
}
}
}

View File

@ -1,7 +0,0 @@
namespace UpTool2.Task
{
internal interface IAppTask
{
public void Run();
}
}

View File

@ -1,49 +0,0 @@
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using UpTool2.Properties;
using UpToolLib;
using UpToolLib.DataStructures;
using UpToolLib.Tool;
namespace UpTool2.Task
{
internal class UploadTask : IAppTask
{
private readonly string _name;
private readonly Action? _postInstall;
public readonly string ZipFile;
public UploadTask(string zipFile, string name, Action? postInstall = null)
{
ZipFile = zipFile;
_name = name;
_postInstall = postInstall;
}
public void Run()
{
#if !DEBUG
try
{
#endif
Guid id = Guid.NewGuid();
while (GlobalVariables.Apps.ContainsKey(id) || Directory.Exists(PathTool.GetAppPath(id)))
id = Guid.NewGuid();
App appI = new App(_name, "Locally installed package, removal only",
GlobalVariables.MinimumVer, "", true, "", id, Color.Red, Resources.C_64.ToBitmap(), false, "");
AppInstall.InstallZip(ZipFile, appI, true);
_postInstall?.Invoke();
#if !DEBUG
}
catch (Exception e1)
{
MessageBox.Show(e1.ToString(), "Install failed");
}
#endif
}
public override string ToString() => $"Install local {Path.GetFileName(ZipFile)}";
}
}

View File

@ -2,13 +2,13 @@
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using UpTool2.Task;
using UpToolLib.v2.TaskQueue;
namespace UpTool2
{
internal static class TaskPreview
{
public static bool Show(ref List<IAppTask> tasks, bool showOk)
public static bool Show(ref List<AppTask> tasks, bool showOk)
{
bool ok = false;
using Form tmp = new Form {Size = new Size(600, 300), MinimumSize = new Size(300, showOk ? 138 : 133)};
@ -25,7 +25,7 @@ namespace UpTool2
};
if (showOk) tmp.Controls.Add(okButton);
tmp.ShowDialog();
tasks = list.Items.OfType<IAppTask>().Where((s, i) => list.GetItemChecked(i)).ToList();
tasks = list.Items.OfType<AppTask>().Where((s, i) => list.GetItemChecked(i)).ToList();
return !showOk || ok;
}
}

View File

@ -6,7 +6,8 @@ using System.Linq;
using System.Reflection;
using UpToolLib;
using UpToolLib.DataStructures;
using UpToolLib.Tool;
using UpToolLib.v1.Tool;
using UpToolLib.v2;
namespace UpToolCLI
{
@ -19,14 +20,14 @@ namespace UpToolCLI
Handler = CommandHandler.Create(List)
});
Command search = new Command("search", "Search for packages")
Command search = new("search", "Search for packages")
{
new Argument<string>("identifier", "Something to identify the app")
};
search.Handler = CommandHandler.Create<string>(Search);
rootCommand.AddCommand(search);
Command show = new Command("show", "Shows package info")
Command show = new("show", "Shows package info")
{
new Argument<string>("identifier", "Something to identify the app")
};
@ -41,8 +42,8 @@ namespace UpToolCLI
private static void List()
{
RepoManagement.GetReposFromDisk();
Console.WriteLine(GlobalVariables.Apps.Where(s => (s.Value.Status & Status.Installed) == Status.Installed)
Program.Lib.V2.RepoManagement.GetReposFromDisk();
Console.WriteLine(Program.Lib.V1.Apps.Where(s => (s.Value.Status & Status.Installed) == Status.Installed)
.ToStringTable(new[]
{
"Name", "State", "Guid"
@ -55,8 +56,8 @@ namespace UpToolCLI
private static void Search(string identifier)
{
RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier);
Program.Lib.V2.RepoManagement.GetReposFromDisk();
App[] apps = Program.Lib.V1.AppExtras.FindApps(identifier);
Console.WriteLine($"Found {apps.Length} app(s)");
if (apps.Length > 0)
Console.WriteLine(apps.ToStringTable(new[]
@ -69,8 +70,8 @@ namespace UpToolCLI
private static void Show(string identifier)
{
RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier);
Program.Lib.V2.RepoManagement.GetReposFromDisk();
App[] apps = Program.Lib.V1.AppExtras.FindApps(identifier);
if (apps.Length == 0)
Console.WriteLine("Package not found.");
else
@ -80,10 +81,10 @@ namespace UpToolCLI
private static void Update()
{
Console.WriteLine("Fetching Repos...");
RepoManagement.FetchRepos();
RepoManagement.GetReposFromDisk();
Program.Lib.V2.RepoManagement.FetchRepos();
Program.Lib.V2.RepoManagement.GetReposFromDisk();
Console.WriteLine();
IEnumerable<App> tmp = GlobalVariables.Apps.Where(s =>
IEnumerable<App> tmp = Program.Lib.V1.Apps.Where(s =>
(s.Value.Status & Status.Updatable) == Status.Updatable).Select(s => s.Value);
IEnumerable<App> apps = tmp as App[] ?? tmp.ToArray();
int updatableCount = apps.Count();
@ -92,7 +93,7 @@ namespace UpToolCLI
: $@"Found {updatableCount} Updates:
{string.Join(Environment.NewLine, apps.Select(s => $"- {s.Name} ({s.Version})"))}");
Version vLocal = Assembly.GetExecutingAssembly().GetName().Version;
Version vOnline = UpdateCheck.OnlineVersion;
Version vOnline = Program.Lib.V2.UpdateChecker.Check().OnlineVersion;
if (vLocal < vOnline)
Console.WriteLine($"uptool is outdated ({vLocal} vs {vOnline}), update using \"uptool upgrade-self\"");
}

View File

@ -9,7 +9,8 @@ using System.Reflection;
using System.Security.Cryptography;
using UpToolLib;
using UpToolLib.DataStructures;
using UpToolLib.Tool;
using UpToolLib.v1.Tool;
using UpToolLib.v2;
using Process = System.Diagnostics.Process;
namespace UpToolCLI
@ -18,14 +19,14 @@ namespace UpToolCLI
{
public static void RegisterCommands(RootCommand rootCommand)
{
Command command = new Command("upgrade-self", "Upgrades UpToolCLI")
Command command = new("upgrade-self", "Upgrades UpToolCLI")
{
new Option<bool>(new[] {"--force", "-f"}, "Overwrites older files")
};
command.Handler = CommandHandler.Create<bool>(UpgradeSelf);
rootCommand.AddCommand(command);
Command start = new Command("start", "Starts an app")
Command start = new("start", "Starts an app")
{
new Argument<string>("identifier", "Something to identify the app"),
new Option<string>(new[] {"--arguments", "--args", "-a"}, () => "", "The arguments to run the file with"),
@ -38,39 +39,41 @@ namespace UpToolCLI
public static void UpgradeSelf(bool force)
{
if (!force && Assembly.GetExecutingAssembly().GetName().Version >= UpdateCheck.OnlineVersion)
PathTool pathTool = Program.Lib.V1.PathTool;
UpdateCheck updateCheck = Program.Lib.V2.UpdateChecker.Check();
if (!force && Assembly.GetExecutingAssembly().GetName().Version >= updateCheck.OnlineVersion)
Console.WriteLine("Already up-to-date");
else
{
Console.WriteLine("Downloading latest");
(bool success, byte[] dl) = Program.Functions.Download(UpdateCheck.Installer);
(bool success, byte[] dl) = Program.Functions.Download(updateCheck.Installer);
if (!success)
throw new Exception("Failed to update");
Console.WriteLine("Verifying");
using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
using (SHA256CryptoServiceProvider sha256 = new())
{
string pkgHash = BitConverter.ToString(sha256.ComputeHash(dl)).Replace("-", string.Empty).ToUpper();
if (pkgHash != UpdateCheck.InstallerHash)
if (pkgHash != updateCheck.InstallerHash)
throw new Exception($@"The hash is not equal to the one stored in the repo:
Package: {pkgHash}
Online: {UpdateCheck.InstallerHash}");
Online: {updateCheck.InstallerHash}");
}
Console.WriteLine("Installing");
if (Directory.Exists(PathTool.GetRelative("Install", "tmp")))
Directory.Delete(PathTool.GetRelative("Install", "tmp"), true);
Directory.CreateDirectory(PathTool.GetRelative("Install", "tmp"));
using (MemoryStream ms = new MemoryStream(dl))
if (Directory.Exists(pathTool.GetRelative("Install", "tmp")))
Directory.Delete(pathTool.GetRelative("Install", "tmp"), true);
Directory.CreateDirectory(pathTool.GetRelative("Install", "tmp"));
using (MemoryStream ms = new(dl))
{
using ZipArchive ar = new ZipArchive(ms);
ar.ExtractToDirectory(PathTool.GetRelative("Install", "tmp"), true);
using ZipArchive ar = new(ms);
ar.ExtractToDirectory(pathTool.GetRelative("Install", "tmp"), true);
}
string file = PathTool.GetRelative("Install", "tmp", "Installer.exe");
string file = pathTool.GetRelative("Install", "tmp", "Installer.exe");
Console.WriteLine($"Starting {file}");
Process.Start(new ProcessStartInfo
{
FileName = file,
Arguments = "i",
WorkingDirectory = PathTool.GetRelative("Install"),
WorkingDirectory = pathTool.GetRelative("Install"),
UseShellExecute = false
});
}
@ -78,8 +81,8 @@ Online: {UpdateCheck.InstallerHash}");
private static void Start(string identifier, string arguments, string file, bool waitForExit)
{
RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier);
Program.Lib.V2.RepoManagement.GetReposFromDisk();
App[] apps = Program.Lib.V1.AppExtras.FindApps(identifier);
if (apps.Length == 0)
Console.WriteLine("Package not found.");
else
@ -88,7 +91,7 @@ Online: {UpdateCheck.InstallerHash}");
if (tmp.Runnable)
{
Console.WriteLine($"Starting {tmp.Name}");
Process tmp1 = AppExtras.RunApp(tmp, file ?? tmp.MainFile, arguments);
Process tmp1 = Program.Lib.V1.AppExtras.RunApp(tmp, file ?? tmp.MainFile, arguments);
if (waitForExit)
tmp1.WaitForExit();
}

View File

@ -8,7 +8,9 @@ using System.Linq;
using System.Reflection;
using UpToolLib;
using UpToolLib.DataStructures;
using UpToolLib.Tool;
using UpToolLib.v1;
using UpToolLib.v1.Tool;
using UpToolLib.v2;
namespace UpToolCLI
{
@ -16,7 +18,7 @@ namespace UpToolCLI
{
public static void RegisterCommands(RootCommand rootCommand)
{
Command install = new Command("install", "Install a package")
Command install = new("install", "Install a package")
{
new Argument<string>("identifier", "Something to identify the app or the file name"),
new Option<bool>(new[] {"--force", "-f"}, "Overwrites older files")
@ -24,7 +26,7 @@ namespace UpToolCLI
install.Handler = CommandHandler.Create<string, bool>(Install);
rootCommand.AddCommand(install);
Command upgrade = new Command("upgrade", "Upgrade a package")
Command upgrade = new("upgrade", "Upgrade a package")
{
new Argument<string>("identifier", "Something to identify the app"),
new Option<bool>(new[] {"--force", "-f"}, "Overwrites older files")
@ -32,7 +34,7 @@ namespace UpToolCLI
upgrade.Handler = CommandHandler.Create<string, bool>(Upgrade);
rootCommand.AddCommand(upgrade);
Command reinstall = new Command("reinstall", "Reinstall a package")
Command reinstall = new("reinstall", "Reinstall a package")
{
new Argument<string>("identifier", "Something to identify the app"),
new Option<bool>(new[] {"--force", "-f"}, "Overwrites older files")
@ -40,14 +42,14 @@ namespace UpToolCLI
reinstall.Handler = CommandHandler.Create<string, bool>(Reinstall);
rootCommand.AddCommand(reinstall);
Command remove = new Command("remove", "Remove a package")
Command remove = new("remove", "Remove a package")
{
new Argument<string>("identifier", "Something to identify the app")
};
remove.Handler = CommandHandler.Create<string>(Remove);
rootCommand.AddCommand(remove);
Command purge = new Command("purge", "Completely remove a package")
Command purge = new("purge", "Completely remove a package")
{
new Argument<string>("identifier", "Something to identify the app")
};
@ -62,16 +64,16 @@ namespace UpToolCLI
private static void Install(string identifier, bool force)
{
RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier);
Program.Lib.V2.RepoManagement.GetReposFromDisk();
App[] apps = Program.Lib.V1.AppExtras.FindApps(identifier);
if (apps.Length == 0)
{
if (File.Exists(identifier))
{
Console.WriteLine("Name:");
string name = Console.ReadLine();
AppInstall.InstallZip(identifier, new App(name, "Locally installed package, removal only",
GlobalVariables.MinimumVer, "", true, "",
Program.Lib.V1.Installer.InstallZip(identifier, Program.Lib.V2.AppFactory.CreateApp(name, "Locally installed package, removal only",
UpToolLibV1.MinimumVer, "", true, "",
Guid.NewGuid(), Color.Red, "", false, ""), force);
Console.WriteLine($"Successfully installed \"{name}\"");
}
@ -89,7 +91,7 @@ namespace UpToolCLI
else
{
Console.WriteLine($"Installing {tmp.Name}");
AppInstall.Install(tmp, true);
Program.Lib.V1.Installer.Install(tmp, true);
}
}
Console.WriteLine("Done!");
@ -97,8 +99,8 @@ namespace UpToolCLI
private static void Upgrade(string identifier, bool force)
{
RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier);
Program.Lib.V2.RepoManagement.GetReposFromDisk();
App[] apps = Program.Lib.V1.AppExtras.FindApps(identifier);
if (apps.Length == 0)
Console.WriteLine("Package not found.");
else
@ -107,7 +109,7 @@ namespace UpToolCLI
if ((tmp.Status & Status.Updatable) == Status.Updatable)
{
Console.WriteLine($"Upgrading {tmp.Name}");
AppExtras.Update(tmp, force);
Program.Lib.V1.AppExtras.Update(tmp, force);
}
else
Console.WriteLine("Package is up-to-date");
@ -117,23 +119,23 @@ namespace UpToolCLI
private static void Reinstall(string identifier, bool force)
{
RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier);
Program.Lib.V2.RepoManagement.GetReposFromDisk();
App[] apps = Program.Lib.V1.AppExtras.FindApps(identifier);
if (apps.Length == 0)
Console.WriteLine("Package not found.");
else
{
App tmp = apps.First();
Console.WriteLine($"Reinstalling {tmp.Name}");
AppExtras.Update(tmp, force);
Program.Lib.V1.AppExtras.Update(tmp, force);
}
Console.WriteLine("Done!");
}
private static void Remove(string identifier)
{
RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier);
Program.Lib.V2.RepoManagement.GetReposFromDisk();
App[] apps = Program.Lib.V1.AppExtras.FindApps(identifier);
if (apps.Length == 0)
Console.WriteLine("Package not found.");
else
@ -142,7 +144,7 @@ namespace UpToolCLI
if ((tmp.Status & Status.Installed) == Status.Installed)
{
Console.WriteLine($"Removing {tmp.Name}");
AppExtras.Remove(tmp, false);
Program.Lib.V1.AppExtras.Remove(tmp, false);
}
else
Console.WriteLine("Package is not installed");
@ -152,8 +154,8 @@ namespace UpToolCLI
private static void Purge(string identifier)
{
RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier);
Program.Lib.V2.RepoManagement.GetReposFromDisk();
App[] apps = Program.Lib.V1.AppExtras.FindApps(identifier);
if (apps.Length == 0)
Console.WriteLine("Package not found.");
else
@ -162,7 +164,7 @@ namespace UpToolCLI
if ((tmp.Status & Status.Installed) == Status.Installed)
{
Console.WriteLine($"Purging {tmp.Name}");
AppExtras.Remove(tmp, true);
Program.Lib.V1.AppExtras.Remove(tmp, true);
}
else
Console.WriteLine("Package is not installed");
@ -172,14 +174,14 @@ namespace UpToolCLI
private static void DistUpgrade()
{
RepoManagement.GetReposFromDisk();
foreach (KeyValuePair<Guid, App> app in GlobalVariables.Apps.Where(s =>
Program.Lib.V2.RepoManagement.GetReposFromDisk();
foreach (KeyValuePair<Guid, App> app in Program.Lib.V1.Apps.Where(s =>
(s.Value.Status & Status.Updatable) == Status.Updatable))
{
Console.WriteLine($"Updating {app.Value.Name}");
AppExtras.Update(app.Value, false);
Program.Lib.V1.AppExtras.Update(app.Value, false);
}
if (Assembly.GetExecutingAssembly().GetName().Version < UpdateCheck.OnlineVersion)
if (Assembly.GetExecutingAssembly().GetName().Version < Program.Lib.V2.UpdateChecker.Check().OnlineVersion)
{
Console.WriteLine("Updating self");
Other.UpgradeSelf(false);

View File

@ -1,24 +1,23 @@
using System;
using System.CommandLine;
using UpToolLib;
using UpToolLib.Tool;
namespace UpToolCLI
{
public static class Program
{
public static readonly UtLibFunctions Functions = new UtLibFunctions();
public static readonly UtLibFunctions Functions = new();
public static bool Basic;
public static UpToolLibMain Lib;
public static int Main(string[] args)
{
MutexLock.Lock();
try
{
Basic = args.Length > 0 && args[0].ToLower() == "--basic";
ExternalFunctionalityManager.Init(Functions);
XmlTool.FixXml();
RootCommand rootCommand = new RootCommand();
Lib = new UpToolLibMain(Functions);
Lib.V1.XmlTool.FixXml();
RootCommand rootCommand = new();
rootCommand.AddGlobalOption(new Option<bool>("--basic", "Use only basic console functionality. Must be the first parameter in the call"));
PackageManagement.RegisterCommands(rootCommand);
@ -35,7 +34,7 @@ namespace UpToolCLI
}
finally
{
MutexLock.Unlock();
Lib?.Dispose();
}
}
}

View File

@ -3,12 +3,13 @@ using System.CommandLine;
using System.CommandLine.Invocation;
using System.Linq;
using System.Xml.Linq;
using UpToolLib.Tool;
using UpToolLib.v1.Tool;
namespace UpToolCLI
{
public class ReposManagement
{
private static string InfoXml => Program.Lib.V1.PathTool.InfoXml;
public static void RegisterCommands(RootCommand rootCommand)
{
rootCommand.AddCommand(new Command("list-repo", "Lists current repositories")
@ -16,7 +17,7 @@ namespace UpToolCLI
Handler = CommandHandler.Create(ListRepo)
});
Command addRepo = new Command("add-repo", "Adds a repository")
Command addRepo = new("add-repo", "Adds a repository")
{
new Argument<string>("name", "The new repositories name"),
new Argument<string>("link", "A link to the repositories XML")
@ -24,7 +25,7 @@ namespace UpToolCLI
addRepo.Handler = CommandHandler.Create<string, string>(AddRepo);
rootCommand.AddCommand(addRepo);
Command removeRepo = new Command("remove-repo", "Removes a repository")
Command removeRepo = new("remove-repo", "Removes a repository")
{
new Argument<string>("name", "The repositories name")
};
@ -34,7 +35,7 @@ namespace UpToolCLI
private static void ListRepo()
{
XDocument doc = XDocument.Load(PathTool.InfoXml);
XDocument doc = XDocument.Load(InfoXml);
XElement repos = doc.Element("meta").Element("Repos");
Console.WriteLine("Current repos:");
Console.WriteLine(repos.Elements("Repo").ToStringTable(new[]
@ -47,17 +48,17 @@ namespace UpToolCLI
private static void AddRepo(string name, string link)
{
XDocument doc = XDocument.Load(PathTool.InfoXml);
XDocument doc = XDocument.Load(InfoXml);
XElement repos = doc.Element("meta").Element("Repos");
repos.Add(new XElement("Repo", new XElement("Name", name),
new XElement("Link", link)));
doc.Save(PathTool.InfoXml);
doc.Save(InfoXml);
Console.WriteLine("Added repo. Remember to update the cache using \"uptool update\"");
}
private static void RemoveRepo(string name)
{
XDocument doc = XDocument.Load(PathTool.InfoXml);
XDocument doc = XDocument.Load(InfoXml);
XElement repos = doc.Element("meta").Element("Repos");
XElement[] sRepos = repos.Elements("Repo")
.Where(s => s.Element("Name").Value.ToLower().StartsWith(name.ToLower())).ToArray();
@ -85,7 +86,7 @@ namespace UpToolCLI
Console.WriteLine($"Removing {t.Element("Name").Value}");
t.Remove();
}
doc.Save(PathTool.InfoXml);
doc.Save(InfoXml);
Console.WriteLine("Removed repo. Remember to update the cache using \"uptool update\"");
}
}

View File

@ -39,9 +39,9 @@ namespace UpToolCLI
public static string ToStringTable(this string[,] arrValues)
{
int[] maxColumnsWidth = GetMaxColumnsWidth(arrValues);
string headerSpliter = new string('-', maxColumnsWidth.Sum(i => i + 3) - 1);
string headerSpliter = new('-', maxColumnsWidth.Sum(i => i + 3) - 1);
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
{
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)

View File

@ -13,7 +13,7 @@ namespace UpToolCLI
{
public Tuple<bool, byte[]> Download(Uri link)
{
using WebClient client = new WebClient();
using WebClient client = new();
byte[] result = new byte[0];
bool finished = false;
bool success = true;
@ -41,10 +41,10 @@ namespace UpToolCLI
public string FetchImageB64(Uri link)
{
using WebClient client = new WebClient();
using WebClient client = new();
using Image image = Image.Load(client.OpenRead(link));
image.Mutate(x => x.Resize(70, 70));
using MemoryStream ms = new MemoryStream();
using MemoryStream ms = new();
image.SaveAsPng(ms);
return Convert.ToBase64String(ms.ToArray());
}

View File

@ -0,0 +1,17 @@
using System;
using Eto.Forms;
namespace UpToolEto.Gtk
{
class MainClass
{
[STAThread]
public static void Main(string[] args)
{
UpToolEto.Main.Entry(new Application(Eto.Platforms.Gtk), () =>
{
});
}
}
}

View File

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\UpToolEto\UpToolEto.csproj"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Eto.Platform.Gtk" Version="2.5.10"/>
</ItemGroup>
</Project>

View File

@ -0,0 +1,38 @@
using System;
using Eto.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace UpToolEto.Wpf
{
class MainClass
{
[STAThread]
public static void Main(string[] args)
{
UpToolEto.Main.Entry(new Application(Eto.Platforms.Wpf), () =>
{
Process[] processes = Process.GetProcessesByName("UpTool2");
if (processes.Length > 0)
BringProcessToFront(processes[0]);
});
}
public static void BringProcessToFront(Process process)
{
IntPtr handle = process.MainWindowHandle;
if (IsIconic(handle))
ShowWindow(handle, 9);
SetForegroundWindow(handle);
}
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr handle);
[DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr handle, int nCmdShow);
[DllImport("User32.dll")]
private static extern bool IsIconic(IntPtr handle);
}
}

View File

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\UpToolEto\UpToolEto.csproj"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Eto.Platform.Wpf" Version="2.5.10"/>
</ItemGroup>
</Project>

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using Eto.Drawing;
using Eto.Forms;
using UpToolLib.v2;
namespace UpToolEto.Controls
{
public class AppList : Scrollable
{
private readonly IDictionary<Guid, App> _apps;
private readonly Action<Guid, App> _itemClickEvent;
private readonly StackLayout _layout;
public AppList(IDictionary<Guid, App> apps, Action<Guid, App> itemClickEvent)
{
_apps = apps;
_itemClickEvent = itemClickEvent;
_layout = new StackLayout
{
Padding = 10,
Orientation = Orientation.Vertical,
Width = 200
};
Content = _layout;
Update();
}
public void Update()
{
_layout.Items.Clear();
foreach ((Guid id, App app) in _apps)
{
_layout.Items.Add(new Button((_, _) => _itemClickEvent(id, app))
{
Text = app.Name,
Image = (Icon)app.Icon,
ImagePosition = ButtonImagePosition.Left,
});
}
}
}
}

View File

@ -0,0 +1,38 @@
using Eto.Drawing;
using Eto.Forms;
using UpToolLib.v2;
namespace UpToolEto.Controls
{
public class AppPanel : Panel
{
private readonly Label _appNameLabel;
private readonly Label _appDescriptionLabel;
public AppPanel()
{
_appDescriptionLabel = new Label();
_appNameLabel = new Label();
_appNameLabel.Font = new Font(_appNameLabel.Font.Family, _appNameLabel.Font.Size * 2);
Content = new StackLayout
{
Items =
{
_appNameLabel,
_appDescriptionLabel
}
};
}
public void FromApp(App app)
{
_appNameLabel.Text = app.Name;
_appDescriptionLabel.Text = app.Description;
}
public void Clear()
{
_appNameLabel.Text = "Welcome to UpTool2";
_appDescriptionLabel.Text = "Select an app to get started";
}
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using Eto.Forms;
using UpToolLib.DataStructures;
namespace UpToolEto.Controls
{
public class RepoItem : StackLayout
{
public RepoItem(Repo repo, int index, Action update, IList<Repo> repos)
{
TextBox name = new()
{
Text = repo.Name
};
name.TextChanged += (_, _) => repo.Name = name.Text;
TextBox link = new()
{
Text = repo.Url
};
link.TextChanged += (_, _) => repo.Url = link.Text;
Orientation = Orientation.Horizontal;
Items.Add(name);
Items.Add(new StackLayoutItem(link, HorizontalAlignment.Stretch, true));
Items.Add(new Button((_, _) =>
{
repos.RemoveAt(index);
update();
})
{
Text = "-"
});
}
}
}

View File

@ -0,0 +1,51 @@
using Eto.Forms;
using UpToolEto.Forms;
using UpToolLib.v2;
namespace UpToolEto.Controls
{
public class UTMenuBar : MenuBar
{
public UTMenuBar(MainForm mainForm, RepoManagement repoManagement, AppList appList)
{
Command reloadRepos = new() {MenuText = "Reload", ToolBarText = "Reload"};
reloadRepos.Executed += (_, _) =>
{
if (Main.Platform.YesNoDialog("This may take some time. Are you sure?", true))
{
repoManagement.FetchRepos();
repoManagement.GetReposFromDisk();
appList.Update();
}
};
Command openSettings = new() {MenuText = "Sources", ToolBarText = "Sources"};
openSettings.Executed += (_, _) => new RepoForm(repoManagement).Show();
Command quitCommand = new() {MenuText = "Quit", Shortcut = Application.Instance.CommonModifier | Keys.Q};
quitCommand.Executed += (_, _) => Application.Instance.Quit();
Command aboutCommand = new() {MenuText = "About Eto..."};
aboutCommand.Executed += (_, _) => new AboutDialog().ShowDialog(mainForm);
Items.Add(new ButtonMenuItem
{
Text = "&File", Items =
{
reloadRepos,
openSettings
}
});
// File submenu
// new ButtonMenuItem { Text = "&Edit", Items = { /* commands/items */ } },
// new ButtonMenuItem { Text = "&View", Items = { /* commands/items */ } },
/*ApplicationItems =
{
// application (OS X) or file menu (others)
new ButtonMenuItem {Text = "&Preferences..."},
},*/
QuitItem = quitCommand;
AboutItem = aboutCommand;
}
}
}

View File

@ -0,0 +1,52 @@
using System;
using System.Net;
using Eto.Drawing;
using Eto.Forms;
namespace UpToolEto.Forms
{
public class DownloadDialog : Form
{
public bool Success = false;
public byte[] Download = new byte[0];
public DownloadDialog(Uri url)
{
Title = "Downloader";
Resizable = false;
Maximizable = false;
Minimizable = false;
WindowStyle = WindowStyle.Utility;
ProgressBar bar = new();
bar.MaxValue = 100;
Content = new StackLayout
{
Padding = 10,
Items =
{
"Downloading " + url,
new StackLayoutItem(bar, HorizontalAlignment.Stretch, true)
}
};
Size = new Size(700, 400);
try
{
WebClient client = new();
client.DownloadProgressChanged += (_, args) =>
{
bar.Value = args.ProgressPercentage;
};
client.DownloadDataCompleted += (_, args) =>
{
Success = true;
Download = args.Result;
Close();
};
client.DownloadDataAsync(url, client);
}
catch
{
Close();
}
}
}
}

View File

@ -0,0 +1,43 @@
using System;
using Eto.Drawing;
using Eto.Forms;
namespace UpToolEto.Forms
{
public class InitScreen : Form
{
private readonly Application _application;
private readonly Label _lab;
public InitScreen(Application application)
{
_application = application;
Title = "UpTool2 Init";
Resizable = false;
Maximizable = false;
Minimizable = false;
WindowStyle = WindowStyle.None;
_lab = new Label();
Label header = new();
header.Font = new Font(header.Font.Family, header.Font.Size * 2);
header.Text = "UpTool2";
Content = new StackLayout
{
Padding = 10,
Items =
{
new StackLayoutItem(header, HorizontalAlignment.Center),
new StackLayoutItem(_lab, HorizontalAlignment.Center)
},
VerticalContentAlignment = VerticalAlignment.Center
};
Shown += (_, _) => Size = new Size(700, 400);
}
public void SetText(string text)
{
Console.WriteLine(text);
_lab.Text = text;
_application.RunIteration();
}
}
}

View File

@ -0,0 +1,36 @@
using Eto.Drawing;
using Eto.Forms;
using UpToolEto.Controls;
using UpToolLib;
//TODO implement tasks queue UI
//TODO keep track of app state
//TODO app filters (search by name/tags)
//TODO add control_upload action_run action_update action_remove action_install
namespace UpToolEto.Forms
{
public partial class MainForm : Form
{
private readonly AppPanel _appPanel;
public MainForm(InitScreen init, UpToolLibMain lib)
{
Title = "UpTool2";
MinimumSize = new Size(600, 100);
AppList appList = new(lib.V1.Apps, (guid, app) => _appPanel.FromApp(app));
_appPanel = new AppPanel();
Content = new StackLayout
{
Padding = 10,
Items =
{
appList,
new StackLayoutItem(_appPanel, true)
},
Orientation = Orientation.Horizontal
};
Menu = new UTMenuBar(this, lib.V2.RepoManagement, appList);
Shown += (_, _) => init.Close();
}
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using Eto.Forms;
using UpToolEto.Controls;
using UpToolLib.DataStructures;
using UpToolLib.v2;
namespace UpToolEto.Forms
{
public class RepoForm : Form
{
private readonly RepoManagement _management;
private List<Repo> _repos = new();
private StackLayout _layout;
public RepoForm(RepoManagement management)
{
_management = management;
_repos.AddRange(management.GetRepos());
Title = "Sources";
_layout = new StackLayout();
Content = _layout;
Update();
}
private void Update()
{
_layout.Items.Clear();
_layout.Items.Add(new StackLayoutItem(new Button((_, _) =>
{
_repos.Add(new Repo
{
Name = "New repo",
Url = "https://example.com/repo.xml"
});
Update();
})
{
Text = "Add",
}, HorizontalAlignment.Stretch));
StackLayout reposLayout = new();
for (int i = 0; i < _repos.Count; i++)
reposLayout.Items.Add(new StackLayoutItem(new RepoItem(_repos[i], i, Update, _repos), HorizontalAlignment.Stretch));
_layout.Items.Add(new StackLayoutItem(new Scrollable{Content = reposLayout}, HorizontalAlignment.Stretch, true));
_layout.Items.Add(new StackLayoutItem(new Button((_, _) =>
{
_management.Save(_repos);
Close();
})
{
Text = "Save"
}, HorizontalAlignment.Stretch));
}
}
}

133
UpToolEto/UpToolEto/Main.cs Normal file
View File

@ -0,0 +1,133 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Security.Cryptography;
using System.Threading;
using System.Xml;
using Eto.Forms;
using UpToolEto.Forms;
using UpToolLib;
using UpToolLib.DataStructures;
using UpToolLib.v1;
using UpToolLib.v1.Tool;
using UpToolLib.v2;
namespace UpToolEto
{
public class Main
{
public static bool Online;
public static IExternalFunctionality Platform;
public static void Entry(Application application, Action activityExistsException)
{
InitScreen init = new(application);
init.Show();
try
{
Platform = new UTLibFunctions();
UpToolLibMain lib = new(Platform);
init.SetText("Initializing paths");
if (!Directory.Exists(lib.V1.PathTool.Dir))
Directory.CreateDirectory(lib.V1.PathTool.Dir);
FixXml(lib.V1.XmlTool, lib.V1.PathTool);
init.SetText("Performing checks");
UpdateCheck updateCheck = null;
try
{
updateCheck = lib.V2.UpdateChecker.Check();
Online = true;
}
catch
{
Online = false;
}
if (Online)
{
if (UpdateCheck(updateCheck, lib.V1.PathTool, init))
{
application.Quit();
return;
}
}
if (!Directory.Exists(lib.V1.PathTool.GetRelative("Apps")))
Directory.CreateDirectory(lib.V1.PathTool.GetRelative("Apps"));
/*if (Online)
{
init.SetText("Fetching repos");
lib.V2.RepoManagement.FetchRepos();
}*/
lib.V2.RepoManagement.GetReposFromDisk();
init.SetText("Opening");
application.Run(new MainForm(init, lib));
}
catch (MutexLockLockedException)
{
init.Close();
MessageBox.Show("Mutex property of other process, quitting");
activityExistsException();
}
}
public static void FixXml(XmlTool xmlTool, PathTool pathTool, bool throwOnError = false)
{
try
{
xmlTool.FixXml();
}
catch (XmlException)
{
if (throwOnError) throw;
MessageBox.Show("Something went wrong while trying to parse XML. Retrying...");
File.Delete(pathTool.InfoXml);
FixXml(xmlTool, pathTool);
}
}
private static bool UpdateCheck(UpdateCheck updateCheck, PathTool pathTool, InitScreen init)
{
init.SetText("Comparing online version");
if (Assembly.GetExecutingAssembly().GetName().Version >= updateCheck.OnlineVersion) return false;
if (PlatformCheck.IsWindows)
{
init.SetText("Downloading latest");
(bool success, byte[] dl) = Platform.Download(updateCheck.Installer);
if (!success)
throw new Exception("Failed to update");
init.SetText("Verifying");
using (SHA256CryptoServiceProvider sha256 = new())
{
string pkgHash = BitConverter.ToString(sha256.ComputeHash(dl)).Replace("-", string.Empty).ToUpper();
if (pkgHash != updateCheck.InstallerHash)
throw new Exception(
$"The hash is not equal to the one stored in the repo:\r\nPackage: {pkgHash}\r\nOnline: {updateCheck.InstallerHash}");
}
init.SetText("Installing");
if (Directory.Exists(pathTool.GetRelative("Install", "tmp")))
Directory.Delete(pathTool.GetRelative("Install", "tmp"), true);
Directory.CreateDirectory(pathTool.GetRelative("Install", "tmp"));
using (MemoryStream ms = new(dl))
{
using ZipArchive ar = new(ms);
ar.ExtractToDirectory(pathTool.GetRelative("Install", "tmp"), true);
}
init.Close();
Process.Start(new ProcessStartInfo
{
FileName = pathTool.GetRelative("Install", "tmp", "Installer.exe"),
Arguments = "i -p",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = pathTool.GetRelative("Install")
});
return true;
}
else
{
MessageBox.Show("A new version is available. Please install it");
return false;
}
}
}
}

View File

@ -0,0 +1,51 @@
using System;
using System.IO;
using System.Net;
using System.Threading;
using Eto.Drawing;
using Eto.Forms;
using UpToolEto.Forms;
using UpToolLib;
using UpToolLib.DataStructures;
namespace UpToolEto
{
public class UTLibFunctions : IExternalFunctionality
{
private const int ImgSize = 32;
public Tuple<bool, byte[]> Download(Uri link)
{
DownloadDialog dlg = new(link);
dlg.Show();
while (dlg.Visible) Thread.Sleep(20);
return new Tuple<bool, byte[]>(dlg.Success, dlg.Download);
}
public string FetchImageB64(Uri link)
{
using WebClient client = new();
using Stream s = client.OpenRead(link);
using Bitmap source = new(s);
using Icon bmp = source.WithSize(ImgSize, ImgSize);
using Bitmap bitmapResized = new(bmp);
using MemoryStream ms = new();
bitmapResized.Save(ms, ImageFormat.Png);
return Convert.ToBase64String(ms.ToArray());
}
public bool YesNoDialog(string text, bool defaultVal) =>
MessageBox.Show(text, MessageBoxButtons.YesNo,
defaultButton: defaultVal ? MessageBoxDefaultButton.Yes : MessageBoxDefaultButton.No) == DialogResult.Yes;
public void OkDialog(string text) => MessageBox.Show(text);
public object GetDefaultIcon() => Bitmap.FromResource("UpToolLib.C_64.ico", typeof(UpToolLibMain)).WithSize(ImgSize, ImgSize);
public object ImageFromB64(string b64) => new Bitmap(Convert.FromBase64String(b64)).WithSize(ImgSize, ImgSize);
public void Log(string text)
{
//TODO implement visual logging
}
}
}

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Eto.Forms" Version="2.5.10" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\UpToolLib\UpToolLib.csproj" />
</ItemGroup>
</Project>

View File

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

@ -0,0 +1,8 @@
namespace UpToolLib.DataStructures
{
public class Repo
{
public string Name { get; set; }
public string Url { get; set; }
}
}

View File

@ -1,14 +0,0 @@
using UpToolLib.DataStructures;
namespace UpToolLib
{
public static class ExternalFunctionalityManager
{
internal static IExternalFunctionality Instance;
public static void Init(IExternalFunctionality externalFunctionality)
{
Instance = externalFunctionality;
}
}
}

View File

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using UpToolLib.DataStructures;
namespace UpToolLib
{
public static class GlobalVariables
{
public const string Windows = "WINDOWS";
public const string Posix = "POSIX";
public static readonly Dictionary<Guid, App> Apps = new Dictionary<Guid, App>();
public static Version MinimumVer => Version.Parse("0.0.0.0");
public static string CurrentPlatform =>
PlatformCheck.IsWindows ? Windows :
PlatformCheck.IsPosix ? Posix : throw new Exception("Unexpeccted PlatformCheck");
}
}

View File

@ -1,43 +0,0 @@
using System;
using System.Threading;
namespace UpToolLib
{
public static class MutexLock
{
private static Mutex _mutex;
private static bool _hasHandle;
public static void Lock()
{
_mutex = new Mutex(false,
"Global\\{c0c1e002-9e13-4e8f-a035-dbdc5128e00e}",
out bool _);
_hasHandle = false;
try
{
_hasHandle = _mutex.WaitOne(5000, false);
if (_hasHandle)
return;
throw new MutexLockLockedException();
}
catch (AbandonedMutexException)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("Mutex abandoned");
#endif
_hasHandle = true;
}
}
public static void Unlock()
{
if (_hasHandle)
_mutex.ReleaseMutex();
}
}
public class MutexLockLockedException : Exception
{
}
}

View File

@ -0,0 +1,8 @@
using System;
namespace UpToolLib
{
public class MutexLockLockedException : Exception
{
}
}

View File

@ -1,25 +0,0 @@
using System;
using System.IO;
using System.Linq;
namespace UpToolLib.Tool
{
public static class PathTool
{
public static string Dir =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UpTool2");
public static string TempPath => GetRelative("tmp");
public static string AppsPath => GetRelative("Apps");
public static string InfoXml => GetRelative("info.xml");
public static string GetRelative(params string[] segments) =>
Path.Combine(new[] {Dir}.Concat(segments).ToArray());
public static string GetAppPath(Guid app) => Path.Combine(AppsPath, app.ToString());
public static string GetDataPath(Guid app) => Path.Combine(GetAppPath(app), "app");
public static string GetInfoPath(Guid app) => Path.Combine(GetAppPath(app), "info.xml");
}
}

View File

@ -6,4 +6,11 @@
<AssemblyVersion>1.0.*</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
<Content Remove="C_64.ico" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="C_64.ico" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,38 @@
using System;
using System.Threading;
using UpToolLib.DataStructures;
using UpToolLib.v1;
using UpToolLib.v2;
namespace UpToolLib
{
public class UpToolLibMain : IDisposable
{
private static Mutex _mutex;
public UpToolLibMain(IExternalFunctionality platform)
{
V1 = new UpToolLibV1(platform);
V2 = new UpToolLibV2(platform, V1.Installer, V1.AppExtras, V1.PathTool, V1.XmlTool, V1.Apps);
_mutex = new Mutex(false,
"Global\\{c0c1e002-9e13-4e8f-a035-dbdc5128e00e}",
out bool _);
try
{
if (_mutex.WaitOne(5000, false))
return;
throw new MutexLockLockedException();
}
catch (AbandonedMutexException)
{
#if DEBUG
_platform.Log("Mutex abandoned");
#endif
}
}
public readonly UpToolLibV1 V1;
public readonly UpToolLibV2 V2;
public void Dispose() => _mutex.ReleaseMutex();
~UpToolLibMain() => Dispose();
}
}

View File

@ -1,32 +0,0 @@
using System;
using System.Xml.Linq;
using UpToolLib.Tool;
namespace UpToolLib
{
public static class UpdateCheck
{
private static XElement _meta;
private static XElement Meta
{
get
{
if (_meta is null) Reload();
return _meta;
}
set => _meta = value;
}
public static Version OnlineVersion => Version.Parse(Meta.Element("Version").Value);
public static Uri Installer => new Uri(Meta.Element("Installer").Value);
public static string InstallerHash => Meta.Element("InstallerHash").Value.ToUpper();
public static Uri App => new Uri(Meta.Element("File").Value);
public static string AppHash => Meta.Element("Hash").Value.ToUpper();
public static void Reload() =>
Reload(XDocument.Load(PathTool.InfoXml).Element("meta").Element("UpdateSource").Value);
public static void Reload(string source) => Meta = XDocument.Load(source).Element("meta");
}
}

View File

@ -1,7 +1,7 @@
using System;
using System.Linq;
namespace UpToolLib
namespace UpToolLib.v1
{
public static class PlatformCheck
{
@ -13,5 +13,11 @@ namespace UpToolLib
.Contains(Environment.OSVersion.Platform);
public static bool IsPosix => !IsWindows;
public const string Windows = "WINDOWS";
public const string Posix = "POSIX";
public static string CurrentPlatform =>
IsWindows ? Windows :
IsPosix ? Posix : throw new Exception("Unexpected PlatformCheck");
}
}

View File

@ -4,15 +4,26 @@ using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using UpToolLib.DataStructures;
using UpToolLib.v2;
namespace UpToolLib.Tool
namespace UpToolLib.v1.Tool
{
public static class AppExtras
public class AppExtras
{
public static Process RunApp(App app) => RunApp(app, app.MainFile, "");
public static Process RunApp(App app, string arguments) => RunApp(app, app.MainFile, arguments);
public static Process RunApp(App app, string file, string arguments) =>
private readonly AppInstall _appInstall;
private readonly PathTool _pathTool;
private readonly IDictionary<Guid, App> _apps;
internal AppExtras(AppInstall appInstall, PathTool pathTool, IDictionary<Guid, App> apps)
{
_appInstall = appInstall;
_pathTool = pathTool;
_apps = apps;
}
public Process RunApp(App app) => RunApp(app, app.MainFile, "");
public Process RunApp(App app, string arguments) => RunApp(app, app.MainFile, arguments);
public Process RunApp(App app, string file, string arguments) =>
Process.Start(
new ProcessStartInfo
{
@ -21,15 +32,15 @@ namespace UpToolLib.Tool
WorkingDirectory = app.DataPath
});
public static void Update(App app, bool overwrite)
public void Update(App app, bool overwrite)
{
Remove(app, overwrite);
AppInstall.Install(app, overwrite);
_appInstall.Install(app, overwrite);
}
public static void Remove(App app, bool deleteAll)
public void Remove(App app, bool deleteAll)
{
string tmp = PathTool.TempPath;
string tmp = _pathTool.TempPath;
if (Directory.Exists(tmp))
Directory.Delete(tmp, true);
Directory.CreateDirectory(tmp);
@ -46,7 +57,7 @@ namespace UpToolLib.Tool
}).WaitForExit();*/
int key = PlatformCheck.IsWindows ? 0 :
File.Exists(Path.Combine(tmp, "Remove.sh")) ? 1 : 2;
ProcessStartInfo prc = new ProcessStartInfo
ProcessStartInfo prc = new()
{
FileName = key switch
{
@ -81,7 +92,7 @@ namespace UpToolLib.Tool
Directory.Delete(app.AppPath, true);
}
private static void CheckDirecory(string tmp, string app)
private void CheckDirecory(string tmp, string app)
{
foreach (string file in Directory.GetFiles(tmp))
{
@ -95,12 +106,11 @@ namespace UpToolLib.Tool
Directory.Delete(app);
}
public static App[] FindApps(string identifier)
public App[] FindApps(string identifier)
{
Dictionary<Guid, App> tmp = GlobalVariables.Apps;
IEnumerable<KeyValuePair<Guid, App>> tmp1 = tmp.Where(s => s.Key.ToString().StartsWith(identifier));
tmp1 = tmp1.Concat(tmp.Where(s => s.Value.Name.Contains(identifier)));
tmp1 = tmp1.Concat(tmp.Where(s => s.Value.Description.Contains(identifier)));
IEnumerable<KeyValuePair<Guid, App>> tmp1 = _apps.Where(s => s.Key.ToString().StartsWith(identifier));
tmp1 = tmp1.Concat(_apps.Where(s => s.Value.Name.Contains(identifier)));
tmp1 = tmp1.Concat(_apps.Where(s => s.Value.Description.Contains(identifier)));
return tmp1.Select(s => s.Value).ToArray();
}
}

View File

@ -5,17 +5,27 @@ using System.IO.Compression;
using System.Security.Cryptography;
using System.Xml.Linq;
using UpToolLib.DataStructures;
using UpToolLib.v2;
namespace UpToolLib.Tool
namespace UpToolLib.v1.Tool
{
public static class AppInstall
public class AppInstall
{
private readonly IExternalFunctionality _platform;
private readonly PathTool _pathTool;
internal AppInstall(IExternalFunctionality platform, PathTool pathTool)
{
_platform = platform;
_pathTool = pathTool;
}
/// <summary>
/// Install an application
/// </summary>
/// <param name="appI">The app to install</param>
/// <param name="force">Set to true to overwrite all old data</param>
public static void Install(App appI, bool force)
public void Install(App appI, bool force)
{
string app = "";
string tmp = "";
@ -24,7 +34,7 @@ namespace UpToolLib.Tool
{
#endif
app = appI.AppPath;
tmp = PathTool.TempPath;
tmp = _pathTool.TempPath;
if (Directory.Exists(tmp))
Directory.Delete(tmp, true);
Directory.CreateDirectory(tmp);
@ -39,10 +49,10 @@ namespace UpToolLib.Tool
if (!Directory.Exists(app))
Directory.CreateDirectory(app);
}
(bool dlSuccess, byte[] dlData) = ExternalFunctionalityManager.Instance.Download(new Uri(appI.File));
(bool dlSuccess, byte[] dlData) = _platform.Download(new Uri(appI.File));
if (!dlSuccess)
throw new Exception("Download failed");
using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
using (SHA256CryptoServiceProvider sha256 = new())
{
string pkgHash = BitConverter.ToString(sha256.ComputeHash(dlData)).Replace("-", string.Empty)
.ToUpper();
@ -71,7 +81,7 @@ Online: {appI.Hash.ToUpper()}");
#endif
}
public static void InstallZip(string zipPath, App meta, bool force)
public void InstallZip(string zipPath, App meta, bool force)
{
string app = "";
string tmp = "";
@ -79,7 +89,7 @@ Online: {appI.Hash.ToUpper()}");
{
app = meta.AppPath;
Directory.CreateDirectory(app);
tmp = PathTool.TempPath;
tmp = _pathTool.TempPath;
if (Directory.Exists(tmp))
Directory.Delete(tmp, true);
Directory.CreateDirectory(tmp);
@ -102,13 +112,13 @@ Online: {appI.Hash.ToUpper()}");
//Use
//PowerShell -Command "Add-Type -AssemblyName PresentationFramework;[System.Windows.MessageBox]::Show('Hello World')"
//for message boxes
private static void CompleteInstall(App app, bool force) => CompleteInstall(app.AppPath, app.Name,
private void CompleteInstall(App app, bool force) => CompleteInstall(app.AppPath, app.Name,
app.Description, app.Version, app.MainFile, force);
private static void CompleteInstall(string appPath, string name, string description, Version version,
private void CompleteInstall(string appPath, string name, string description, Version version,
string mainFile, bool force)
{
string tmp = PathTool.TempPath;
string tmp = _pathTool.TempPath;
ZipFile.ExtractToDirectory(Path.Combine(appPath, "package.zip"), tmp);
if (force)
Directory.Move(Path.Combine(tmp, "Data"), Path.Combine(appPath, "app"));
@ -117,7 +127,7 @@ Online: {appI.Hash.ToUpper()}");
CopyAll(Path.Combine(tmp, "Data"), Path.Combine(appPath, "app"));
Directory.Delete(Path.Combine(tmp, "Data"), true);
}
XElement el = new XElement("app", new XElement("Name", name), new XElement("Description", description),
XElement el = new("app", new XElement("Name", name), new XElement("Description", description),
new XElement("Version", version));
if (mainFile != null)
el.Add(new XElement(new XElement("MainFile", mainFile)));
@ -151,7 +161,7 @@ Online: {appI.Hash.ToUpper()}");
}).WaitForExit();*/
int key = PlatformCheck.IsWindows ? 0 :
File.Exists(Path.Combine(tmp, "Install.sh")) ? 1 : 2;
ProcessStartInfo prc = new ProcessStartInfo
ProcessStartInfo prc = new()
{
FileName = key switch
{
@ -175,7 +185,7 @@ Online: {appI.Hash.ToUpper()}");
Process.Start(prc)?.WaitForExit();
}
private static void CopyAll(string source, string target)
private void CopyAll(string source, string target)
{
if (string.Equals(Path.GetFullPath(source), Path.GetFullPath(target),
StringComparison.CurrentCultureIgnoreCase))

View File

@ -0,0 +1,25 @@
using System;
using System.IO;
using System.Linq;
namespace UpToolLib.v1.Tool
{
public class PathTool
{
public string Dir =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UpTool2");
public string TempPath => GetRelative("tmp");
public string AppsPath => GetRelative("Apps");
public string InfoXml => GetRelative("info.xml");
public string GetRelative(params string[] segments) =>
Path.Combine(new[] {Dir}.Concat(segments).ToArray());
public string GetAppPath(Guid app) => Path.Combine(AppsPath, app.ToString());
public string GetDataPath(Guid app) => Path.Combine(GetAppPath(app), "app");
public string GetInfoPath(Guid app) => Path.Combine(GetAppPath(app), "info.xml");
}
}

View File

@ -1,18 +1,28 @@
using System.IO;
using System.Linq;
using System.Xml.Linq;
using UpToolLib.DataStructures;
namespace UpToolLib.Tool
namespace UpToolLib.v1.Tool
{
public static class XmlTool
public class XmlTool
{
public static void FixXml()
private readonly IExternalFunctionality _platform;
private readonly PathTool _pathTool;
internal XmlTool(IExternalFunctionality platform, PathTool pathTool)
{
if (!Directory.Exists(PathTool.AppsPath))
Directory.CreateDirectory(PathTool.AppsPath);
if (!File.Exists(PathTool.InfoXml) || XDocument.Load(PathTool.InfoXml).Element("meta") == null)
new XElement("meta").Save(PathTool.InfoXml);
XDocument x = XDocument.Load(PathTool.InfoXml);
_platform = platform;
_pathTool = pathTool;
}
public void FixXml()
{
if (!Directory.Exists(_pathTool.AppsPath))
Directory.CreateDirectory(_pathTool.AppsPath);
if (!File.Exists(_pathTool.InfoXml) || XDocument.Load(_pathTool.InfoXml).Element("meta") == null)
new XElement("meta").Save(_pathTool.InfoXml);
XDocument x = XDocument.Load(_pathTool.InfoXml);
XElement meta = x.Element("meta");
if (meta.Element("UpdateSource") == null)
meta.Add(new XElement("UpdateSource"));
@ -32,7 +42,7 @@ namespace UpToolLib.Tool
meta.Add(new XElement("Repos"));
if (meta.Element("Repos").Elements("Repo").Count() == 0)
{
if (ExternalFunctionalityManager.Instance.YesNoDialog(
if (_platform.YesNoDialog(
"No active repository was detected. Add the default repo?", false))
{
meta.Element("Repos").Add(new XElement("Repo", new XElement("Name", "UpTool2 official Repo"),
@ -53,7 +63,7 @@ namespace UpToolLib.Tool
"https://gitlab.com/uptool/UpTool2/-/snippets/1988600/raw/master/Repo.xml");
if (meta.Element("LocalRepo") == null)
meta.Add(new XElement("LocalRepo"));
x.Save(PathTool.InfoXml);
x.Save(_pathTool.InfoXml);
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using UpToolLib.DataStructures;
using UpToolLib.v1.Tool;
using UpToolLib.v2;
namespace UpToolLib.v1
{
public class UpToolLibV1
{
internal UpToolLibV1(IExternalFunctionality platform)
{
PathTool = new PathTool();
XmlTool = new XmlTool(platform, PathTool);
Installer = new AppInstall(platform, PathTool);
AppExtras = new AppExtras(Installer, PathTool, Apps);
}
public readonly AppExtras AppExtras;
public readonly AppInstall Installer;
public readonly PathTool PathTool;
public readonly XmlTool XmlTool;
public readonly IDictionary<Guid, App> Apps = new Dictionary<Guid, App>();
public static Version MinimumVer => Version.Parse("0.0.0.0");
}
}

View File

@ -3,10 +3,11 @@ using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using UpToolLib.Tool;
using UpToolLib.DataStructures;
using UpToolLib.v1.Tool;
using static System.Environment;
namespace UpToolLib.DataStructures
namespace UpToolLib.v2
{
public struct App : IEquatable<App>
{
@ -21,9 +22,10 @@ namespace UpToolLib.DataStructures
public readonly object Icon;
public readonly bool Runnable;
public readonly string MainFile;
private readonly PathTool _pathTool;
public App(string name, string description, Version version, string file, bool local, string hash, Guid iD,
Color color, object icon, bool runnable, string mainFile)
internal App(string name, string description, Version version, string file, bool local, string hash, Guid iD,
Color color, object icon, bool runnable, string mainFile, PathTool pathTool)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Description = description ?? throw new ArgumentNullException(nameof(description));
@ -36,6 +38,7 @@ namespace UpToolLib.DataStructures
Icon = icon ?? throw new ArgumentNullException(nameof(icon));
Runnable = runnable;
MainFile = mainFile ?? throw new ArgumentNullException(nameof(mainFile));
_pathTool = pathTool;
}
public Status Status
@ -75,8 +78,8 @@ Object Hash Code: {GetHashCode()}";
public static bool operator !=(App left, App right) => !(left == right);
public string AppPath => PathTool.GetAppPath(Id);
public string DataPath => PathTool.GetDataPath(Id);
public string InfoPath => PathTool.GetInfoPath(Id);
public string AppPath => _pathTool.GetAppPath(Id);
public string DataPath => _pathTool.GetDataPath(Id);
public string InfoPath => _pathTool.GetInfoPath(Id);
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Drawing;
using UpToolLib.DataStructures;
using UpToolLib.v1.Tool;
namespace UpToolLib.v2
{
public class AppFactory
{
private readonly PathTool _pathTool;
internal AppFactory(PathTool pathTool) => _pathTool = pathTool;
public App CreateApp(string name, string description, Version version, string file, bool local, string hash,
Guid iD, Color color, object icon, bool runnable, string mainFile) =>
new(name, description, version, file, local, hash, iD, color, icon, runnable, mainFile, _pathTool);
}
}

View File

@ -5,16 +5,60 @@ using System.IO;
using System.Linq;
using System.Xml.Linq;
using UpToolLib.DataStructures;
using UpToolLib.v1;
using UpToolLib.v1.Tool;
namespace UpToolLib.Tool
namespace UpToolLib.v2
{
public static class RepoManagement
public class RepoManagement
{
public static void FetchRepos()
private readonly IExternalFunctionality _platform;
private readonly XmlTool _xmlTool;
private readonly PathTool _pathTool;
private readonly AppFactory _appFactory;
private readonly IDictionary<Guid, App> _apps;
public RepoManagement(IExternalFunctionality platform, XmlTool xmlTool, PathTool pathTool, AppFactory appFactory, IDictionary<Guid, App> apps)
{
XmlTool.FixXml();
XElement meta = XDocument.Load(PathTool.InfoXml).Element("meta");
List<XElement> tmpAppsList = new List<XElement>();
_platform = platform;
_xmlTool = xmlTool;
_pathTool = pathTool;
_appFactory = appFactory;
_apps = apps;
}
public void Save(IEnumerable<Repo> repos)
{
XDocument doc = XDocument.Load(_pathTool.InfoXml);
XElement reposEl = doc.Element("meta").Element("Repos");
reposEl.RemoveNodes();
foreach (Repo repo in repos)
reposEl.Add(new XElement("Repo", new XElement("Name", repo.Name), new XElement("Link", repo.Url)));
doc.Save(_pathTool.InfoXml);
}
public IEnumerable<Repo> GetRepos()
{
_xmlTool.FixXml();
XDocument doc = XDocument.Load(_pathTool.InfoXml);
XElement reposEl = doc.Element("meta").Element("Repos");
List<Repo> repos = new();
foreach (XElement repo in reposEl.Elements("Repo"))
{
repos.Add(new Repo
{
Name = repo.Element("Name").Value,
Url = repo.Element("Link").Value
});
}
return repos.ToArray();
}
public void FetchRepos()
{
_xmlTool.FixXml();
XElement meta = XDocument.Load(_pathTool.InfoXml).Element("meta");
List<XElement> tmpAppsList = new();
List<string> repArr = meta.Element("Repos").Elements("Repo").Select(s => s.Element("Link").Value).Distinct()
.ToList();
int i = 0;
@ -25,7 +69,7 @@ namespace UpToolLib.Tool
try
{
#endif
ExternalFunctionalityManager.Instance.Log($"[{i + 1}] Loading {repArr[i]}");
_platform.Log($"[{i + 1}] Loading {repArr[i]}");
status = $"Loading {repArr[i]}";
XDocument repo = XDocument.Load(new Uri(repArr[i]).AbsoluteUri);
status = $"Extracting repolinks";
@ -36,11 +80,11 @@ namespace UpToolLib.Tool
!tmpAppsList.Any(a => a.Element("ID").Value == app.Element("ID").Value) ||
!tmpAppsList
.Where(a => a.Element("ID").Value == app.Element("ID").Value).Any(a =>
GetVer(a.Element("Version")) >= app.Element("Version").GetVer())).ToArray()
GetVer(a.Element("Version")) >= GetVer(app.Element("Version")))).ToArray()
.Concat(repo.Element("repo").Elements("applink")
.Select(s =>
{
ExternalFunctionalityManager.Instance.Log($"- Loading {s.Value}");
_platform.Log($"- Loading {s.Value}");
status = $"Fetching app data tag: {s.Value}";
XElement ret = XDocument.Load(new Uri(s.Value).AbsoluteUri)
.Element("app");
@ -69,8 +113,7 @@ namespace UpToolLib.Tool
{
tmpAppsList.Last()
.Add(new XElement("Icon",
ExternalFunctionalityManager.Instance.FetchImageB64(
new Uri(app.Element("Icon").Value))));
_platform.FetchImageB64(new Uri(app.Element("Icon").Value))));
}
catch
{
@ -78,9 +121,9 @@ namespace UpToolLib.Tool
}
tmpAppsList.Last().Add(new XElement("Platform",
app.Element("Platform") == null ||
!new[] {GlobalVariables.Posix, GlobalVariables.Windows}.Contains(app.Element("Platform")
!new[] {PlatformCheck.Posix, PlatformCheck.Windows}.Contains(app.Element("Platform")
.Value)
? GlobalVariables.CurrentPlatform
? PlatformCheck.CurrentPlatform
: app.Element("Platform").Value));
XElement app1 = app;
if (tmpAppsList.Count(a => a.Element("ID").Value == app1.Element("ID").Value) > 1)
@ -92,7 +135,7 @@ namespace UpToolLib.Tool
}
catch (Exception e)
{
ExternalFunctionalityManager.Instance.OkDialog(
_platform.OkDialog(
$"Failed to load repo: {repArr[i]}{Environment.NewLine}Last status was: {status}{Environment.NewLine}{e}");
}
#endif
@ -105,29 +148,29 @@ namespace UpToolLib.Tool
XElement repos = meta.Element("LocalRepo");
repos.RemoveNodes();
tmpAppsList.ForEach(app => repos.Add(app));
meta.Save(PathTool.InfoXml);
meta.Save(_pathTool.InfoXml);
}
private static Version GetVer(this XElement el) =>
private Version GetVer(XElement el) =>
int.TryParse(el.Value, out int i) ? new Version(0, 0, 0, i) : Version.Parse(el.Value);
/// <summary>
/// Load the repository cache
/// </summary>
/// <param name="errorHandler">Function to call on an exception, will ask the user whether he wants to quit</param>
public static void GetReposFromDisk()
public void GetReposFromDisk()
{
GlobalVariables.Apps.Clear();
string xml = PathTool.InfoXml;
_apps.Clear();
string xml = _pathTool.InfoXml;
XDocument.Load(xml).Element("meta").Element("LocalRepo").Elements().ToList().ForEach(app =>
{
if (app.Element("Platform").Value != GlobalVariables.CurrentPlatform) return;
if (app.Element("Platform").Value != PlatformCheck.CurrentPlatform) return;
Guid id = Guid.Parse(app.Element("ID").Value);
string locInPath = PathTool.GetInfoPath(id);
string locInPath = _pathTool.GetInfoPath(id);
XElement locIn = File.Exists(locInPath) ? XDocument.Load(locInPath).Element("app") : app;
if (int.TryParse(app.Element("Version").Value, out _))
app.Element("Version").Value = GlobalVariables.MinimumVer.ToString();
GlobalVariables.Apps.Add(id, new App(
app.Element("Version").Value = UpToolLibV1.MinimumVer.ToString();
_apps.Add(id, _appFactory.CreateApp(
locIn.Element("Name").Value,
locIn.Element("Description").Value,
Version.Parse(app.Element("Version").Value),
@ -137,38 +180,38 @@ namespace UpToolLib.Tool
id,
Color.White,
app.Element("Icon") == null
? ExternalFunctionalityManager.Instance.GetDefaultIcon()
: ExternalFunctionalityManager.Instance.ImageFromB64(app.Element("Icon").Value),
? _platform.GetDefaultIcon()
: _platform.ImageFromB64(app.Element("Icon").Value),
locIn.Element("MainFile") != null || app.Element("MainFile") != null,
locIn.Element("MainFile") == null
? app.Element("MainFile") == null ? "" : app.Element("MainFile").Value
: locIn.Element("MainFile").Value
));
});
Directory.GetDirectories(PathTool.AppsPath)
Directory.GetDirectories(_pathTool.AppsPath)
.Where(s => Guid.TryParse(Path.GetFileName(s), out Guid guid) &&
!GlobalVariables.Apps.ContainsKey(guid)).ToList().ForEach(s =>
!_apps.ContainsKey(guid)).ToList().ForEach(s =>
{
Guid tmp = Guid.Parse(Path.GetFileName(s));
try
{
XElement data = XDocument.Load(PathTool.GetInfoPath(tmp)).Element("app");
GlobalVariables.Apps.Add(tmp,
new App($"(local) {data.Element("Name").Value}", data.Element("Description").Value,
GlobalVariables.MinimumVer, "", true, "", tmp, Color.Red,
ExternalFunctionalityManager.Instance.GetDefaultIcon(),
XElement data = XDocument.Load(_pathTool.GetInfoPath(tmp)).Element("app");
_apps.Add(tmp,
_appFactory.CreateApp($"(local) {data.Element("Name").Value}", data.Element("Description").Value,
UpToolLibV1.MinimumVer, "", true, "", tmp, Color.Red,
_platform.GetDefaultIcon(),
data.Element("MainFile") != null,
data.Element("MainFile") == null ? "" : data.Element("MainFile").Value));
}
catch (Exception e)
{
if (ExternalFunctionalityManager.Instance.YesNoDialog(
if (_platform.YesNoDialog(
$@"An error occured while loading this local repo:
{e.Message}
Do you want to exit? Otherwise the folder will be deleted, possibly causeing problems later.", false))
Environment.Exit(0);
else
Directory.Delete(PathTool.GetAppPath(tmp), true);
Directory.Delete(_pathTool.GetAppPath(tmp), true);
}
});
}

View File

@ -0,0 +1,13 @@
using UpToolLib.DataStructures;
namespace UpToolLib.v2.TaskQueue
{
public abstract class AppTask
{
public abstract void Run();
public AppTask(IExternalFunctionality platform) => Platform = platform;
protected IExternalFunctionality Platform { get; }
}
}

View File

@ -1,17 +1,18 @@
using System;
using System.Windows.Forms;
using UpToolLib.DataStructures;
using UpToolLib.Tool;
using UpToolLib.v1.Tool;
namespace UpTool2.Task
namespace UpToolLib.v2.TaskQueue
{
internal class InstallTask : IKnownAppTask
public class InstallTask : KnownAppTask
{
private readonly AppInstall _installer;
private readonly Action? _postInstall;
public InstallTask(App app, Action? postInstall = null)
internal InstallTask(IExternalFunctionality platform, AppInstall installer, App app, Action? postInstall) : base(platform)
{
App = app;
_installer = installer;
_postInstall = postInstall;
}
@ -26,15 +27,14 @@ namespace UpTool2.Task
try
{
#endif
AppInstall.Install(App, true);
_installer.Install(App, true);
_postInstall?.Invoke();
trying = false;
#if !DEBUG
}
catch (Exception e1)
{
trying = MessageBox.Show(e1.ToString(), "Install failed", MessageBoxButtons.RetryCancel) ==
DialogResult.Retry;
trying = Platform.YesNoDialog("Install failed. Retry?\r\nException=" + e1, true);
}
#endif
}

View File

@ -1,11 +1,10 @@
using UpToolLib.DataStructures;
namespace UpTool2.Task
namespace UpToolLib.v2.TaskQueue
{
internal abstract class IKnownAppTask : IAppTask
public abstract class KnownAppTask : AppTask
{
public abstract App App { get; }
public abstract void Run();
public override string ToString() => $"{TrimEnd(GetType().Name, "Task")} {App.Name}";
@ -18,5 +17,9 @@ namespace UpTool2.Task
return result;
}
protected KnownAppTask(IExternalFunctionality platform) : base(platform)
{
}
}
}

View File

@ -1,17 +1,18 @@
using System;
using System.Windows.Forms;
using UpToolLib.DataStructures;
using UpToolLib.Tool;
using UpToolLib.v1.Tool;
namespace UpTool2.Task
namespace UpToolLib.v2.TaskQueue
{
internal class RemoveTask : IKnownAppTask
public class RemoveTask : KnownAppTask
{
private readonly AppExtras _extras;
private readonly Action? _postInstall;
public RemoveTask(App app, Action? postInstall = null)
internal RemoveTask(IExternalFunctionality platform, AppExtras extras, App app, Action? postInstall) : base(platform)
{
App = app;
_extras = extras;
_postInstall = postInstall;
}
@ -23,13 +24,13 @@ namespace UpTool2.Task
try
{
#endif
AppExtras.Remove(App, true);
_extras.Remove(App, true);
_postInstall?.Invoke();
#if !DEBUG
}
catch (Exception e1)
{
MessageBox.Show(e1.ToString(), "Removal failed");
Platform.OkDialog("Removal failed.\r\nException=" + e1);
}
#endif
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using UpToolLib.DataStructures;
using UpToolLib.v1.Tool;
namespace UpToolLib.v2.TaskQueue
{
public class TaskFactory
{
private IExternalFunctionality _platform;
private readonly AppInstall _installer;
private readonly AppExtras _extras;
private readonly PathTool _pathTool;
private readonly AppFactory _appFactory;
private readonly IDictionary<Guid, App> _apps;
internal TaskFactory(IExternalFunctionality platform, AppInstall installer, AppExtras extras, PathTool pathTool, AppFactory appFactory, IDictionary<Guid, App> apps)
{
_platform = platform;
_installer = installer;
_extras = extras;
_pathTool = pathTool;
_appFactory = appFactory;
_apps = apps;
}
public KnownAppTask CreateInstall(App app, Action? postInstall = null) => new InstallTask(_platform, _installer, app, postInstall);
public KnownAppTask CreateRemove(App app, Action? postInstall = null) => new RemoveTask(_platform, _extras, app, postInstall);
public KnownAppTask CreateUpdate(App app, Action? postInstall = null) => new UpdateTask(_platform, _extras, app, postInstall);
public AppTask CreateUpload(string zipFile, string name, Action? postInstall = null) => new UploadTask(_platform, _installer, _appFactory, _pathTool, _apps, zipFile, name, postInstall);
}
}

View File

@ -1,17 +1,18 @@
using System;
using System.Windows.Forms;
using UpToolLib.DataStructures;
using UpToolLib.Tool;
using UpToolLib.v1.Tool;
namespace UpTool2.Task
namespace UpToolLib.v2.TaskQueue
{
internal class UpdateTask : IKnownAppTask
public class UpdateTask : KnownAppTask
{
private readonly AppExtras _extras;
private readonly Action? _postInstall;
public UpdateTask(App app, Action? postInstall = null)
internal UpdateTask(IExternalFunctionality platform, AppExtras extras, App app, Action? postInstall) : base(platform)
{
App = app;
_extras = extras;
_postInstall = postInstall;
}
@ -23,13 +24,13 @@ namespace UpTool2.Task
try
{
#endif
AppExtras.Update(App, false);
_extras.Update(App, false);
_postInstall?.Invoke();
#if !DEBUG
}
catch (Exception e1)
{
MessageBox.Show(e1.ToString(), "Install failed");
Platform.OkDialog("Update failed.\r\nException=" + e1);
}
#endif
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using UpToolLib.DataStructures;
using UpToolLib.v1;
using UpToolLib.v1.Tool;
namespace UpToolLib.v2.TaskQueue
{
public class UploadTask : AppTask
{
private readonly string _name;
private readonly Action? _postInstall;
private readonly AppInstall _installer;
private readonly AppFactory _appFactory;
private readonly PathTool _pathTool;
private readonly IDictionary<Guid, App> _apps;
public readonly string ZipFile;
internal UploadTask(IExternalFunctionality platform, AppInstall installer, AppFactory appFactory, PathTool pathTool, IDictionary<Guid, App> apps, string zipFile, string name, Action? postInstall) : base(platform)
{
_installer = installer;
_appFactory = appFactory;
_pathTool = pathTool;
_apps = apps;
ZipFile = zipFile;
_name = name;
_postInstall = postInstall;
}
public override void Run()
{
#if !DEBUG
try
{
#endif
Guid id = Guid.NewGuid();
while (_apps.ContainsKey(id) || Directory.Exists(_pathTool.GetAppPath(id)))
id = Guid.NewGuid();
App appI = _appFactory.CreateApp(_name, "Locally installed package, removal only",
UpToolLibV1.MinimumVer, "", true, "", id, Color.Red, Platform.GetDefaultIcon(), false, "");
_installer.InstallZip(ZipFile, appI, true);
_postInstall?.Invoke();
#if !DEBUG
}
catch (Exception e1)
{
Platform.OkDialog("Upload failed.\r\nException=" + e1);
}
#endif
}
public override string ToString() => $"Install local {Path.GetFileName(ZipFile)}";
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using UpToolLib.DataStructures;
using UpToolLib.v1.Tool;
using UpToolLib.v2.TaskQueue;
namespace UpToolLib.v2
{
public class UpToolLibV2
{
internal UpToolLibV2(IExternalFunctionality platform, AppInstall install, AppExtras extras, PathTool pathTool, XmlTool xmlTool, IDictionary<Guid, App> apps)
{
AppFactory = new AppFactory(pathTool);
UpdateChecker = new UpdateChecker(pathTool);
TaskFactory = new TaskFactory(platform, install, extras, pathTool, AppFactory, apps);
RepoManagement = new RepoManagement(platform, xmlTool, pathTool, AppFactory, apps);
}
public readonly UpdateChecker UpdateChecker;
public readonly TaskFactory TaskFactory;
public readonly AppFactory AppFactory;
public readonly RepoManagement RepoManagement;
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Xml.Linq;
namespace UpToolLib.v2
{
public class UpdateCheck
{
public readonly Version OnlineVersion;
public readonly Uri Installer;
public readonly string InstallerHash;
public readonly Uri App;
public readonly string AppHash;
public UpdateCheck(XElement meta)
{
OnlineVersion = Version.Parse(meta.Element("Version").Value);
Installer = new Uri(meta.Element("Installer").Value);
InstallerHash = meta.Element("InstallerHash").Value.ToUpper();
App = new Uri(meta.Element("File").Value);
AppHash = meta.Element("Hash").Value.ToUpper();
}
}
}

View File

@ -0,0 +1,13 @@
using System.Xml.Linq;
using UpToolLib.v1.Tool;
namespace UpToolLib.v2
{
public class UpdateChecker
{
private readonly PathTool _pathTool;
public UpdateCheck Check() => Check(XDocument.Load(_pathTool.InfoXml).Element("meta").Element("UpdateSource").Value);
public UpdateCheck Check(string source) => new(XDocument.Load(source).Element("meta"));
internal UpdateChecker(PathTool pathTool) => _pathTool = pathTool;
}
}