The move!

This commit is contained in:
Jamie.Rees 2017-05-16 08:31:44 +01:00
commit 25526cc4d9
1147 changed files with 85 additions and 8524 deletions

View file

@ -0,0 +1,35 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2017 Jamie Rees
// File: AppType.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
namespace Ombi.Updater
{
public enum AppType
{
Normal,
Console,
Service
}
}

View file

@ -0,0 +1,38 @@
using Ombi.Common;
using Ombi.Common.EnvironmentInfo;
using Ombi.Common.Processes;
namespace Ombi.Updater
{
public class DetectApplicationType
{
public DetectApplicationType()
{
_processProvider = new ProcessProvider();
_serviceProvider = new ServiceProvider(_processProvider);
}
private readonly IServiceProvider _serviceProvider;
private readonly IProcessProvider _processProvider;
public AppType GetAppType()
{
if (OsInfo.IsNotWindows)
{
// Technically it is the console, but it has been renamed for mono (Linux/OS X)
return AppType.Normal;
}
if (_serviceProvider.ServiceExist(ServiceProvider.OmbiServiceName))
{
return AppType.Service;
}
if (_processProvider.Exists(ProcessProvider.OmbiProcessName))
{
return AppType.Console;
}
return AppType.Normal;
}
}
}

View file

@ -0,0 +1,289 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2017 Jamie Rees
// File: InstallService.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
using NLog;
using Ombi.Common;
using Ombi.Common.EnvironmentInfo;
using Ombi.Common.Processes;
namespace Ombi.Updater
{
public class InstallService
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly IProcessProvider _processProvider = new ProcessProvider();
private string BackupPath { get; set; }
private string TempPath { get; set; }
public void Start(UpdateStartupContext ctx)
{
var dector = new DetectApplicationType();
var processId = _processProvider.FindProcessByName(ProcessProvider.OmbiProcessName)?.FirstOrDefault()?.Id ?? -1;
// Log if process is -1
var dir = CreateTempPath();
TempPath = Path.Combine(dir.FullName, "OmbiUpdate.zip");
using (var client = new WebClient())
{
client.DownloadProgressChanged += (s, e) =>
{
Console.WriteLine($"{e.ProgressPercentage}%");
};
client.DownloadFile(ctx.DownloadPath, TempPath);
}
var appType = dector.GetAppType();
_processProvider.FindProcessByName(ProcessProvider.OmbiProcessName);
var installationFolder = GetInstallationDirectory(ctx);
var terminator = new TerminateOmbi(new ServiceProvider(_processProvider), _processProvider);
if (OsInfo.IsWindows)
{
terminator.Terminate(processId);
}
try
{
BackupCurrentVersion();
EmptyInstallationFolder();
using (var archive = ZipFile.OpenRead(TempPath))
{
foreach (var entry in archive.Entries)
{
var fullname = string.Empty;
if (entry.FullName.Contains("Release/")) // Don't extract the release folder, we are already in there
{
fullname = entry.FullName.Replace("Release/", string.Empty);
}
if (entry.Name.Contains("UpdateService"))
{
fullname = entry.FullName.Replace("UpdateService", "UpdateService_New");
}
var fullPath = Path.Combine(PathUp(Path.GetDirectoryName(Application.ExecutablePath),1),fullname);
if (string.IsNullOrEmpty(entry.Name))
{
Directory.CreateDirectory(fullPath);
}
else
{
if (entry.Name.Contains("Updater"))
{
continue;
}
entry.ExtractToFile(fullPath, true);
Console.WriteLine("Restored {0}", entry.FullName);
}
}
}
// Need to install here
}
catch (Exception e)
{
Console.WriteLine(e);
RestoreBackup();
throw;
}
finally
{
var startOmbi = new StartOmbi(new ServiceProvider(_processProvider), _processProvider);
if (OsInfo.IsWindows)
{
startOmbi.Start(appType, installationFolder);
}
else
{
terminator.Terminate(processId);
Logger.Info("Waiting for external auto-restart.");
for (int i = 0; i < 5; i++)
{
System.Threading.Thread.Sleep(1000);
if (_processProvider.Exists(ProcessProvider.OmbiProcessName))
{
Logger.Info("Ombi was restarted by external process.");
break;
}
}
if (!_processProvider.Exists(ProcessProvider.OmbiProcessName))
{
startOmbi.Start(appType, installationFolder, ctx.StartupArgs);
}
}
}
}
private DirectoryInfo CreateTempPath()
{
try
{
var location = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Updater)).Location ?? string.Empty);
var path = Path.Combine(location, "UpdateTemp");
return Directory.CreateDirectory(path);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine();
Environment.Exit(1);
return null;
}
}
public void RestoreBackup()
{
Console.WriteLine("Update failed, restoring backup");
using (var archive = ZipFile.OpenRead(BackupPath))
{
foreach (var entry in archive.Entries)
{
var fullPath = Path.Combine(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath)), entry.FullName);
if (string.IsNullOrEmpty(entry.Name))
{
Directory.CreateDirectory(fullPath);
}
if (entry.Name.Contains("UpdateService"))
{
continue;
}
else
{
if (entry.Name.Contains("Ombi.Updater"))
{
entry.ExtractToFile(fullPath + "_Updated", true);
continue;
}
entry.ExtractToFile(fullPath, true);
Console.WriteLine("Update failed, restoring backup");
}
}
}
}
private string GetInstallationDirectory(UpdateStartupContext startupContext)
{
Logger.Debug("Using process ID to find installation directory: {0}", startupContext.ProcessId);
var exeFileInfo = new FileInfo(_processProvider.GetProcessById(startupContext.ProcessId).StartPath);
Logger.Debug("Executable location: {0}", exeFileInfo.FullName);
return exeFileInfo.DirectoryName;
}
private void BackupCurrentVersion()
{
Console.WriteLine("Backing up the current version");
try
{
var applicationPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(InstallService)).Location ?? string.Empty) ?? string.Empty;
var dir = Directory.CreateDirectory(Path.Combine(applicationPath, "BackupSystem"));
var allfiles = Directory.GetFiles(applicationPath, "*.*", SearchOption.AllDirectories);
BackupPath = Path.Combine(dir.FullName, "OmbiBackup.zip");
CheckAndDelete(BackupPath);
using (var fileStream = new FileStream(BackupPath, FileMode.CreateNew))
using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
{
foreach (var file in allfiles)
{
if (file.Contains("BackupSystem"))
continue;
var info = Path.GetFileName(file);
archive.CreateEntryFromFile(file, info);
}
}
Console.WriteLine("All backed up!");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine();
Environment.Exit(1);
}
}
private void CheckAndDelete(string filePath)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
private void EmptyInstallationFolder()
{
var applicationPath = PathUp(Path.GetDirectoryName(Assembly.GetAssembly(typeof(InstallService)).Location ?? string.Empty) ?? string.Empty,1);
var allfiles = Directory.GetFiles(applicationPath, "*.*", SearchOption.AllDirectories);
foreach (var file in allfiles)
{
if(file.Contains("BackupSystem") || file.Contains("UpdateService") || file.Contains(".sqlite")) continue;
CheckAndDelete(file);
}
}
static string PathUp(string path, int up)
{
if (up == 0)
return path;
for (int i = path.Length - 1; i >= 0; i--)
{
if (path[i] == Path.DirectorySeparatorChar)
{
up--;
if (up == 0)
return path.Substring(0, i);
}
}
return null;
}
}
public class UpdateStartupContext
{
public int ProcessId { get; set; }
public string DownloadPath { get; set; }
public string StartupArgs { get; set; }
}
}

View file

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{EBE6FC1C-7B4B-47E9-AF54-0EE0604A2BE5}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Ombi.Updater</RootNamespace>
<AssemblyName>Ombi.Updater</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\UpdateService\</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\Updater\</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<ItemGroup>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.3.6\lib\net45\NLog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.IO.Compression.FileSystem" />
<Reference Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Compile Include="AppType.cs" />
<Compile Include="DetectApplicationType.cs" />
<Compile Include="InstallService.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StartOmbi.cs" />
<Compile Include="TerminateOmbi.cs" />
<Compile Include="UpdateEngine\BackupAndRestore.cs" />
<Compile Include="Updater.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\Ombi.Common\Ombi.Common.csproj">
<Project>{bfd45569-90cf-47ca-b575-c7b0ff97f67b}</Project>
<Name>Ombi.Common</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<PropertyGroup>
<PostBuildEvent>(ROBOCOPY "$(ProjectDir)bin\$(ConfigurationName)\UpdateService" "$(SolutionDir)Ombi.UI\bin\$(ConfigurationName)\UpdateService" "*")^&amp; IF %25ERRORLEVEL%25 LEQ 2 exit 0
exit 0</PostBuildEvent>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,40 @@
using System;
using System.Linq;
using System.Windows.Forms;
using Ombi.Common.Processes;
namespace Ombi.Updater
{
class MainClass
{
public static void Main (string[] args)
{
var i = new InstallService();
var context = ParseArgs(args);
i.Start(context);
//Console.WriteLine ("Starting Ombi updater");
// var s = new Updater();
// if (args.Length >= 2)
// {
// s.Start(args[0], args[1]);
// }
// else
// {
// s.Start(args[0], string.Empty);
// }
}
private static UpdateStartupContext ParseArgs(string[] args)
{
var proc = new ProcessProvider();
var ombiProc = proc.FindProcessByName("Ombi").FirstOrDefault().Id;
return new UpdateStartupContext
{
DownloadPath = args[0],
ProcessId = ombiProc,
StartupArgs = args.Length > 1 ? args[1] : string.Empty
};
}
}
}

View file

@ -0,0 +1,27 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Ombi.Updater")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct("Ombi.Updater")]
[assembly: AssemblyCopyright ("TidusJar")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

View file

@ -0,0 +1,99 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2017 Jamie Rees
// File: StartOmbi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.IO;
using NLog;
using Ombi.Common;
using Ombi.Common.Processes;
using IServiceProvider = Ombi.Common.IServiceProvider;
namespace Ombi.Updater
{
public interface IStartOmbi
{
void Start(AppType appType, string installationFolder, string args);
void Start(AppType app, string installationFolder);
}
public class StartOmbi : IStartOmbi
{
private readonly IServiceProvider _serviceProvider;
private readonly IProcessProvider _processProvider;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public StartOmbi(IServiceProvider serviceProvider, IProcessProvider processProvider)
{
_serviceProvider = serviceProvider;
_processProvider = processProvider;
}
public void Start(AppType app, string installationFolder)
{
Start(app, installationFolder, string.Empty);
}
public void Start(AppType appType, string installationFolder, string args)
{
_logger.Info("Starting Ombi");
if (appType == AppType.Service)
{
try
{
StartService();
}
catch (InvalidOperationException e)
{
_logger.Warn(e, "Couldn't start Ombi Service (Most likely due to permission issues). falling back to console.");
StartConsole(installationFolder, args);
}
}
else if (appType == AppType.Console)
{
StartConsole(installationFolder, args);
}
}
private void StartService()
{
_logger.Info("Starting Ombi service");
_serviceProvider.Start(ServiceProvider.OmbiServiceName);
}
private void StartConsole(string installationFolder, string args)
{
Start(installationFolder, "Ombi.exe", args);
}
private void Start(string installationFolder, string fileName, string args)
{
_logger.Info("Starting {0}", fileName);
var path = Path.Combine(installationFolder, fileName);
_processProvider.SpawnNewProcess(path);
}
}
}

View file

@ -0,0 +1,88 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2017 Jamie Rees
// File: TerminateOmbi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using NLog;
using Ombi.Common;
using Ombi.Common.EnvironmentInfo;
using Ombi.Common.Processes;
using IServiceProvider = Ombi.Common.IServiceProvider;
namespace Ombi.Updater
{
public interface ITerminateOmbi
{
void Terminate(int processId);
}
public class TerminateOmbi : ITerminateOmbi
{
private readonly IServiceProvider _serviceProvider;
private readonly IProcessProvider _processProvider;
private static Logger _logger = LogManager.GetCurrentClassLogger();
public TerminateOmbi(IServiceProvider serviceProvider, IProcessProvider processProvider)
{
_serviceProvider = serviceProvider;
_processProvider = processProvider;
}
public void Terminate(int processId)
{
if (OsInfo.IsWindows)
{
_logger.Info("Stopping all running services");
if (_serviceProvider.ServiceExist(ServiceProvider.OmbiServiceName))
{
try
{
_logger.Info("Ombi Service is installed and running");
_serviceProvider.Stop(ServiceProvider.OmbiServiceName);
}
catch (Exception e)
{
_logger.Error(e, "couldn't stop service");
}
}
_logger.Info("Killing all running processes");
_processProvider.KillAll(ProcessProvider.OmbiProcessName);
}
else
{
_logger.Info("Killing all running processes");
_processProvider.KillAll(ProcessProvider.OmbiProcessName);
_processProvider.Kill(processId);
}
}
}
}

View file

@ -0,0 +1,37 @@
//using NLog;
//namespace Ombi.Updater.UpdateEngine
//{
// public interface IBackupAndRestore
// {
// void Backup(string source);
// void Restore(string target);
// }
// public class BackupAndRestore : IBackupAndRestore
// {
// private readonly IDiskTransferService _diskTransferService;
// private readonly IAppFolderInfo _appFolderInfo;
// private readonly Logger _logger;
// public BackupAndRestore(IDiskTransferService diskTransferService, IAppFolderInfo appFolderInfo, Logger logger)
// {
// _diskTransferService = diskTransferService;
// _appFolderInfo = appFolderInfo;
// _logger = logger;
// }
// public void Backup(string source)
// {
// _logger.Info("Creating backup of existing installation");
// _diskTransferService.MirrorFolder(source, _appFolderInfo.GetUpdateBackUpFolder());
// }
// public void Restore(string target)
// {
// _logger.Info("Attempting to rollback upgrade");
// var count = _diskTransferService.MirrorFolder(_appFolderInfo.GetUpdateBackUpFolder(), target);
// _logger.Info("Rolled back {0} files", count);
// }
// }
//}

211
Old/Ombi.Updater/Updater.cs Normal file
View file

@ -0,0 +1,211 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: Updater.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
namespace Ombi.Updater
{
public class Updater
{
private string BackupPath { get; set; }
private bool Error { get; set; }
private string TempPath { get; set; }
public void RestoreBackup()
{
Console.WriteLine("Update failed, restoring backup");
using (var archive = ZipFile.OpenRead(BackupPath))
{
foreach (var entry in archive.Entries)
{
var fullPath = Path.Combine(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath)), entry.FullName);
if (string.IsNullOrEmpty(entry.Name))
{
Directory.CreateDirectory(fullPath);
}
else
{
if (entry.Name.Contains("Ombi.Updater"))
{
entry.ExtractToFile(fullPath + "_Updated", true);
continue;
}
entry.ExtractToFile(fullPath, true);
Console.WriteLine("Update failed, restoring backup");
}
}
}
}
public void Start(string downloadPath, string launchOptions)
{
try
{
BackupCurrentVersion();
var dir = CreateTempPath();
TempPath = Path.Combine(dir.FullName, "OmbiUpdate.zip");
CheckAndDelete(TempPath);
Console.WriteLine("Downloading new version");
using (var client = new WebClient())
{
client.DownloadProgressChanged += (s, e) =>
{
Console.WriteLine($"{e.ProgressPercentage}%");
};
client.DownloadFile(downloadPath, TempPath);
}
Console.WriteLine("Downloaded!");
// Replace files
using (var archive = ZipFile.OpenRead(TempPath))
{
foreach (var entry in archive.Entries)
{
var fullname = string.Empty;
if (entry.FullName.Contains("Release/")) // Don't extract the release folder, we are already in there
{
fullname = entry.FullName.Replace("Release/", string.Empty);
}
var fullPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), fullname);
if (string.IsNullOrEmpty(entry.Name))
{
Directory.CreateDirectory(fullPath);
}
else
{
if (entry.Name.Contains("Ombi.Updater"))
{
entry.ExtractToFile(fullPath + "_Updated", true);
continue;
}
entry.ExtractToFile(fullPath, true);
Console.WriteLine("Restored {0}", entry.FullName);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Oops... Looks like we cannot update!");
Console.ReadLine();
Error = true;
}
finally
{
File.Delete(TempPath);
if (Error)
{
RestoreBackup();
}
FinishUpdate(launchOptions);
}
}
private void BackupCurrentVersion()
{
Console.WriteLine("Backing up the current version");
try
{
var applicationPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Updater)).Location ?? string.Empty) ?? string.Empty;
var dir = Directory.CreateDirectory(Path.Combine(applicationPath, "BackupSystem"));
var allfiles = Directory.GetFiles(applicationPath, "*.*", SearchOption.AllDirectories);
BackupPath = Path.Combine(dir.FullName, "OmbiBackup.zip");
CheckAndDelete(BackupPath);
using (var fileStream = new FileStream(BackupPath, FileMode.CreateNew))
using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
{
foreach (var file in allfiles)
{
if (file.Contains("BackupSystem"))
continue;
var info = Path.GetFileName(file);
archive.CreateEntryFromFile(file, info);
}
}
Console.WriteLine("All backed up!");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine();
Environment.Exit(1);
}
}
private void CheckAndDelete(string filePath)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
private DirectoryInfo CreateTempPath()
{
try {
var location = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Updater)).Location ?? string.Empty);
var path = Path.Combine(location, "UpdateTemp");
return Directory.CreateDirectory(path);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine();
Environment.Exit(1);
return null;
}
}
private void FinishUpdate(string launchOptions)
{
var args = Error ? "-u 2" : "-u 1";
var startInfo = new ProcessStartInfo($"{launchOptions}Ombi.exe") { Arguments = args, UseShellExecute = true };
Process.Start(startInfo);
Environment.Exit(0);
}
}
}

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NLog" version="4.3.6" targetFramework="net45" />
<package id="Polly-Signed" version="4.3.0" targetFramework="net45" />
</packages>