Skip to content

Commit

Permalink
okay so hopefully i can update control now too
Browse files Browse the repository at this point in the history
  • Loading branch information
Olfi01 committed Oct 19, 2017
1 parent 9c7f4ed commit bd87df9
Show file tree
Hide file tree
Showing 10 changed files with 216 additions and 13 deletions.
6 changes: 6 additions & 0 deletions ControlUpdater/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
52 changes: 52 additions & 0 deletions ControlUpdater/ControlUpdater.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4CA0144D-EC95-4069-8001-2640D31CE70B}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ControlUpdater</RootNamespace>
<AssemblyName>ControlUpdater</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
27 changes: 27 additions & 0 deletions ControlUpdater/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ControlUpdater
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 2) return;
string pathToCopyTo = args[0];
string newFilePath = args[1];
Thread.Sleep(5000); //give time to stop old program
if (File.Exists(pathToCopyTo)) File.Delete(pathToCopyTo);
File.Copy(newFilePath, pathToCopyTo);
string exePath = Path.Combine(Path.GetDirectoryName(pathToCopyTo), "WAIBControl.exe");
ProcessStartInfo psi = new ProcessStartInfo(exePath);
Process.Start(psi);
}
}
}
36 changes: 36 additions & 0 deletions ControlUpdater/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("ControlUpdater")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP Inc.")]
[assembly: AssemblyProduct("ControlUpdater")]
[assembly: AssemblyCopyright("Copyright © HP Inc. 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]

// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("4ca0144d-ec95-4069-8001-2640d31ce70b")]

// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
11 changes: 10 additions & 1 deletion WhoAmIBot.sln
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26430.16
VisualStudioVersion = 15.0.26730.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WhoAmIBot", "WhoAmIBot\WhoAmIBot.csproj", "{BC4059AA-80EE-4E63-BFA2-A340644AF78D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApp", "TestApp\TestApp.csproj", "{E055C068-021E-4877-9B42-E3797387D5A8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WhoAmIBotNode", "WhoAmIBotNode\WhoAmIBotNode.csproj", "{C6802A38-760F-4E9C-A28C-607AD9ED66B1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ControlUpdater", "ControlUpdater\ControlUpdater.csproj", "{4CA0144D-EC95-4069-8001-2640D31CE70B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -27,8 +29,15 @@ Global
{C6802A38-760F-4E9C-A28C-607AD9ED66B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C6802A38-760F-4E9C-A28C-607AD9ED66B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C6802A38-760F-4E9C-A28C-607AD9ED66B1}.Release|Any CPU.Build.0 = Release|Any CPU
{4CA0144D-EC95-4069-8001-2640D31CE70B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4CA0144D-EC95-4069-8001-2640D31CE70B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4CA0144D-EC95-4069-8001-2640D31CE70B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4CA0144D-EC95-4069-8001-2640D31CE70B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0D3FCF82-A2E1-4118-BDE2-41934D13569C}
EndGlobalSection
EndGlobal
13 changes: 7 additions & 6 deletions WhoAmIBot/Classes/Node.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,22 @@ namespace WhoAmIBotSpace.Classes
public class Node
{
public Process Process { get; }
private AnonymousPipeServerStream Pipe { get; }
private NamedPipeServerStream Pipe { get; }
public NodeState State { get; set; } = NodeState.Primary;
public string Path { get; set; }
private List<string> queue = new List<string>();
private Thread QThread;
public event EventHandler<Node> NodeStopped;

public Node(string path)
{
Console.WriteLine("Initializing Node at {0}", path);
QThread = new Thread(Queue_Thread);
Path = path;
Process = new Process();
Process.StartInfo.FileName = path;
Pipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
Process.StartInfo.Arguments = Pipe.GetClientHandleAsString();
Pipe = new NamedPipeServerStream(path, PipeDirection.Out);
Process.StartInfo.Arguments = "\"" + path.Trim('"') + "\"";
Process.StartInfo.UseShellExecute = false;
}

Expand All @@ -38,7 +38,7 @@ public void Start(string token)
Pipe.WaitForPipeDrain();
QThread.Start();
}

public void Stop()
{
QThread.Abort();
Expand Down Expand Up @@ -68,6 +68,7 @@ private void Queue_Thread()
{
while (true)
{
try { Pipe.WaitForConnection(); } catch (InvalidOperationException) { }
while (queue.Count < 1) ;
var data = queue[0];
sw.WriteLine(data);
Expand All @@ -90,7 +91,7 @@ public void Queue(string data)
queue.Add(data);
}
}

public enum NodeState
{
Primary,
Expand Down
14 changes: 14 additions & 0 deletions WhoAmIBot/Classes/RestartEventArgs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace WhoAmIBotSpace.Classes
{
public class RestartEventArgs
{
public string NewDllPath { get; }
public string OldDllPath { get; }

public RestartEventArgs(string dllPath, string newDllPath)
{
OldDllPath = dllPath;
NewDllPath = newDllPath;
}
}
}
60 changes: 58 additions & 2 deletions WhoAmIBot/WhoAmIBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
using System.Linq;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Security.Permissions;
using System.Reflection;

namespace WhoAmIBotSpace
{
Expand Down Expand Up @@ -43,12 +43,17 @@ public class WhoAmIBot : FlomBot
"WhoAmIBot\\");
private const string dateTimeFileFormat = "yyyy-MM-dd-HH-mm-ss";
private static readonly string defaultNodeDirectory = Path.Combine(appDataBaseDir, "default\\");
private static readonly string controlUpdaterPath = Path.Combine(appDataBaseDir,
"git\\ControlUpdater\\bin\\Release\\ControlUpdater.exe");
private static readonly string gitNodeDirectory = Path.Combine(appDataBaseDir, "git\\");
#endregion
#region Fields
private SQLiteConnection sqliteConn;
private List<Node> Nodes = new List<Node>();
#endregion
#region Events
public event EventHandler<RestartEventArgs> Restart;
#endregion

#region Helpers
private bool GlobalAdminExists(long id)
Expand Down Expand Up @@ -191,7 +196,7 @@ public override bool StopBot()
Nodes.Remove(Nodes[0]);
continue;
}
Nodes[0].Stop();
if (Nodes[0].State != NodeState.Stopping) Nodes[0].SoftStop();
}
client.OnReceiveError -= Client_OnReceiveError;
client.OnReceiveGeneralError -= Client_OnReceiveError;
Expand Down Expand Up @@ -231,6 +236,16 @@ protected override void Client_OnUpdate(object sender, UpdateEventArgs e)
return;
}
}
else if (cmd == "/updatecontrol")
{
if (e.Update.Message.From.Id == Flom)
{
client.SendTextMessageAsync(e.Update.Message.Chat.Id, "Updating Control. You should try /ping in " +
"about ten seconds, given that all games have already finished.");
UpdateControl();
return;
}
}
if (StandaloneCommandExists(cmd))
{
var node = Nodes.FirstOrDefault(x => x.State == NodeState.Primary);
Expand Down Expand Up @@ -291,6 +306,11 @@ private void Client_OnCallbackQueryUpdateChecker(object sender, CallbackQueryEve
case "update":
Update(cmsg);
break;
case "updatecontrol":
client.EditMessageTextAsync(cmsg.Chat.Id, cmsg.MessageId, "Updating Control. You should try /ping in " +
"about ten seconds, given that all games have already finished.");
UpdateControl();
break;
case "dontUpdate":
client.EditMessageTextAsync(cmsg.Chat.Id, cmsg.MessageId, "Okay, no work for me :)");
break;
Expand Down Expand Up @@ -357,6 +377,42 @@ public static void DeepCopy(DirectoryInfo source, DirectoryInfo target)
file.CopyTo(Path.Combine(target.FullName, file.Name));

}

public void UpdateControl()
{
StopBot();

string path = Assembly.GetExecutingAssembly().CodeBase;
if (path.StartsWith("file:///")) path = path.Substring(8).Replace("/", "\\");
#region Update git
if (!Directory.Exists(appDataBaseDir)) Directory.CreateDirectory(appDataBaseDir);
if (!Directory.Exists(gitNodeDirectory)) Directory.CreateDirectory(gitNodeDirectory);
string firstDir = Path.Combine(gitNodeDirectory, "first.bat");
if (!File.Exists(firstDir)) File.Copy("Updater\\first.bat", firstDir);
string runDir = Path.Combine(gitNodeDirectory, "run.bat");
if (!File.Exists(runDir)) File.Copy("Updater\\run.bat", runDir);
Process first = new Process();
first.StartInfo.FileName = firstDir;
first.StartInfo.UseShellExecute = false;
first.StartInfo.WorkingDirectory = Path.GetDirectoryName(firstDir);
first.Start();
first.WaitForExit();
Process run = new Process();
run.StartInfo.FileName = runDir;
run.StartInfo.UseShellExecute = false;
run.StartInfo.WorkingDirectory = Path.GetDirectoryName(runDir);
run.Start();
run.WaitForExit();
string newDir = Path.Combine(appDataBaseDir, $"WhoAmIBotNode_{DateTime.Now.ToString(dateTimeFileFormat)}\\");
if (!Directory.Exists(newDir)) Directory.CreateDirectory(newDir);
string gitDirToCopy = Path.Combine(gitNodeDirectory, "WhoAmIBot\\WhoAmIBotNode\\bin\\Release");
DeepCopy(new DirectoryInfo(gitDirToCopy), new DirectoryInfo(newDir));
#endregion
newDir = Path.Combine(newDir, "WhoAmIBot.dll");
Restart?.Invoke(this, new RestartEventArgs(path, newDir));
ProcessStartInfo psi = new ProcessStartInfo(controlUpdaterPath, "\"" + path.Trim('"') + "\" \"" + newDir.Trim('"') + "\"");
Process.Start(psi);
}
#endregion

#region Language
Expand Down
1 change: 1 addition & 0 deletions WhoAmIBot/WhoAmIBot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
<Compile Include="Helpers\Extensions.cs" />
<Compile Include="Helpers\Flom.cs" />
<Compile Include="Helpers\Strings.cs" />
<Compile Include="Classes\RestartEventArgs.cs" />
<Compile Include="WhoAmIBot.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Expand Down
9 changes: 5 additions & 4 deletions WhoAmIBotNode/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -483,8 +483,9 @@ private static void Dispose()
static void Main(string[] args)
{
if (args.Length < 1) return;
using (PipeStream pipeClient = new AnonymousPipeClientStream(PipeDirection.In, args[0]))
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", args[0].Trim('"'), PipeDirection.In))
{
pipeClient.Connect();
using (var sr = new StreamReader(pipeClient))
{
string data;
Expand Down Expand Up @@ -533,9 +534,8 @@ static void Main(string[] args)
State = NodeState.Stopped;
running = false;
}
continue;
}
if (!string.IsNullOrEmpty(data))
else if (!string.IsNullOrEmpty(data))
{
HandleData(data);
}
Expand Down Expand Up @@ -1243,7 +1243,8 @@ private static void Getgames_Command(Message msg)
foreach (var s in list)
{
if (string.IsNullOrWhiteSpace(s)) continue;
var t = client.SendTextMessageAsync(msg.Chat.Id, s, replyMarkup: ReplyMarkupMaker.InlineGetGames(NodeGames, msg.Chat.Id));
var t = client.SendTextMessageAsync(msg.Chat.Id, s, replyMarkup: ReplyMarkupMaker.InlineGetGames(NodeGames, msg.Chat.Id),
parseMode: ParseMode.Html);
t.Wait();
sent.Add(t.Result);
}
Expand Down

0 comments on commit bd87df9

Please sign in to comment.