Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
TauAkiou committed Oct 18, 2020
1 parent 622cbde commit b4af7a2
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 111 deletions.
18 changes: 5 additions & 13 deletions AmongUsCapture/IPC/DBus/IConnectLink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,19 @@ namespace AmongUsCapture.DBus
[DBusInterface("org.AmongUsCapture.ConnectLink")]
public interface IConnectLink : IDBusObject
{
Task<IDisposable> WatchConnectInfoAsync(Action<string> handler);
Task SendConnectUriAsync(string uri);
}

public class IPCLink : IConnectLink
{
string _connectlink;
public string ConnectLink
{
get { return _connectlink; }
set
{
_connectlink = value;
SentLink?.Invoke(_connectlink);
}
}
public ObjectPath ObjectPath => new ObjectPath("/org/AmongUsCapture/ConnectLink");
public event Action<string> SentLink;

public Task<IDisposable> WatchConnectInfoAsync(Action<string> handler)
public Task SendConnectUriAsync(string uri)
{
return SignalWatcher.AddAsync(this, nameof(SentLink), handler);
// Call event and send URI.
SentLink?.Invoke(uri);
return Task.CompletedTask;
}
}
}
146 changes: 94 additions & 52 deletions AmongUsCapture/IPC/DBus/IPCadapterDBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,11 @@ namespace AmongUsCapture.DBus
{
class IPCadapterDBus : IPCadapter
{
private Thread _dbusProcessingThread;
private CancellationTokenSource _cancellation = new CancellationTokenSource();
private Connection _dbusconnection;
private IConnectLink _ipclink;
private bool _isListening;

private bool _serverIsStarted;
private bool _isHostInstance;
private Task _serverTask;
public override URIStartResult HandleURIStart(string[] args)
{
var myProcessId = Process.GetCurrentProcess().Id;
Expand All @@ -43,13 +42,13 @@ public override URIStartResult HandleURIStart(string[] args)
Console.WriteLine(Program.GetExecutablePath());

//mutex = new Mutex(true, appName, out var createdNew);
bool createdNew = false;
_isHostInstance = false;
var wasURIStart = args.Length > 0 && args[0].StartsWith(UriScheme + "://");
var result = URIStartResult.CONTINUE;

if (!File.Exists(Path.Join(Settings.StorageLocation, ".amonguscapture.pid")))
{
createdNew = true;
_isHostInstance = true;
}
else
{
Expand All @@ -66,38 +65,35 @@ public override URIStartResult HandleURIStart(string[] args)
var capproc = Process.GetProcessById(pidint);
var assmbname = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var runnername = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

if (!capproc.ProcessName.Contains("dotnet"))
var iscapture = false;

foreach (ProcessModule mod in capproc.Modules)
{
// We're just going to assume that a dotnet process that matches this set of parameters
// is a running capture process.
throw new ArgumentException();

// If we find amonguscapturedll in the modules, we can be certain
// that the located pid is, in fact, an AmongUsCapture process.
if (mod.ModuleName == "AmongUsCapture.dll")
{
iscapture = true;
break;
}
}
else if (!capproc.ProcessName.Contains(Path.GetFileName(runnername)))
{
throw new ArgumentException();
}


if (capproc.HasExited)
{
if (!iscapture || capproc.HasExited)
throw new ArgumentException();
}
}
catch (ArgumentException e)
{
// Process doesn't exist. Clear the file.
Console.WriteLine($"Found stale PID file containing {pid}.");
File.Delete(Path.Join(Settings.StorageLocation, ".amonguscapture.pid"));
createdNew = true;
_isHostInstance = true;
}
}
}

}

if (createdNew)
if (_isHostInstance)
{
using (var pidwriter = File.CreateText(Path.Join(Settings.StorageLocation, ".amonguscapture.pid")))
{
Expand All @@ -106,20 +102,18 @@ public override URIStartResult HandleURIStart(string[] args)
}


if (!createdNew) // send it to already existing instance if applicable, then close
if (!_isHostInstance) // send it to already existing instance if applicable, then close
{
if (wasURIStart) SendToken(args[0]).Wait();

return URIStartResult.CLOSE;
}
else if (wasURIStart) // URI start on new instance, continue as normal but also handle current argument
{
// if we are running, we create a file lock with our process in it.
// Also attach the pid delete handler from Program.

result = URIStartResult.PARSE;
}

// Register the xdg-mime handler for discord links.
RegisterProtocol();

return result;
Expand All @@ -136,10 +130,16 @@ private static void RegisterProtocol()
if (!File.Exists(xdg_file))
{
var executingassmb = System.Reflection.Assembly.GetExecutingAssembly().Location;
Console.WriteLine(executingassmb);
if (Path.HasExtension("dll"))
{
executingassmb = "dotnet " + executingassmb;
}
else
{
executingassmb = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
Console.WriteLine(executingassmb);
}

var xdg_file_write = new string[]
{
Expand Down Expand Up @@ -189,16 +189,20 @@ private static void RegisterProtocol()

public override async Task<bool> SendToken(string jsonText)
{
// Delay the send until we know for certain the server is started.
// If this isn't a host instance, we don't care.
while (!_serverIsStarted && _isHostInstance)
await Task.Delay(500);

// Send the token via DBus.
using (Connection conn = new Connection(Address.Session))
{
await conn.ConnectAsync();

var _ipclink = conn.CreateProxy<IConnectLink>("org.AmongUsCapture.ConnectLink",
"/org/AmongUsCapture/ConnectLink");

var obj = new IPCLink();
await conn.RegisterObjectAsync(obj);
await conn.RegisterServiceAsync("org.AmongUsCapture.ipc", ServiceRegistrationOptions.None);

obj.ConnectLink = jsonText;
await _ipclink.SendConnectUriAsync(jsonText);
}

return true;
Expand All @@ -210,55 +214,93 @@ public override void SendToken(string host, string connectCode)
OnTokenEvent(st);
}

public async override Task RegisterMinion()
public override Task RegisterMinion()
{
Task.Factory.StartNew(async () =>
_serverTask = Task.Factory.StartNew(async () =>
{

using (_dbusconnection = new Connection(Address.Session))
try
{
await _dbusconnection.ConnectAsync();

_ipclink = _dbusconnection.CreateProxy<IConnectLink>("org.AmongUsCapture.ConnectLink",
"/org/AmongUsCapture/ConnectLink");
using (Connection conn = new Connection(Address.Session))
{
await conn.ConnectAsync();

await _ipclink.WatchConnectInfoAsync(RespondToDbus);
var obj = new IPCLink();
await conn.RegisterObjectAsync(obj);
await conn.RegisterServiceAsync("org.AmongUsCapture.ConnectLink",
ServiceRegistrationOptions.None);

_isListening = true;
obj.SentLink += RespondToDbus;

while (!_cancellation.IsCancellationRequested)
{
_cancellation.Token.ThrowIfCancellationRequested();
await Task.Delay(int.MaxValue);
_serverIsStarted = true;

while (!_cancellation.IsCancellationRequested)
{
_cancellation.Token.ThrowIfCancellationRequested();
await Task.Delay(int.MaxValue);
}
}
}
catch (OperationCanceledException e)
{
Console.WriteLine("Cancel called - terminating DBus loop.");
}
});

return Task.CompletedTask;
}

public override void startWithToken(string uri)
{
OnTokenEvent(StartToken.FromString(uri));
}

public override bool Cancel()
public override async Task<bool> Cancel()
{
if (!_cancellation.IsCancellationRequested)
{
_cancellation.Cancel();
await CleanPid();
await _serverTask;
return true;
}

return false;
}

private void RespondToDbus(string signalresponse)
private Task CleanPid()
{
Settings.conInterface.WriteModuleTextColored("DBus", Color.Silver,
$"Received new message on DBus: \"{signalresponse}\"");
// Make sure the pidfile is cleaned up if we have one.
var pidfile = Path.Join(Settings.StorageLocation, ".amonguscapture.pid");

signalresponse = signalresponse.Trim('\r', '\n');
if (File.Exists(pidfile))
{
int pid;
bool fileread;
using (var pidread = File.OpenText(Path.Join(Settings.StorageLocation, ".amonguscapture.pid")))
{
fileread = Int32.TryParse(pidread.ReadLine(), out pid);
}

if (!fileread)
{
// Bad read, file must be corrupt. Clear pidfile.
File.Delete(pidfile);
}

if (pid == Process.GetCurrentProcess().Id)
{
// This is our process. Delete file.
File.Delete(pidfile);
}
}

return Task.CompletedTask;
}

private void RespondToDbus(string signalresponse)
{
Settings.conInterface.WriteModuleTextColored("DBus", Color.Silver,
$"Received DBus Method Call: \"{signalresponse}\"");

var token = StartToken.FromString(signalresponse);

OnTokenEvent(token);
Expand Down
5 changes: 1 addition & 4 deletions AmongUsCapture/IPC/IPCadapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ abstract class IPCadapter
protected const string FriendlyName = "AmongUs Capture";
protected Mutex mutex;




private static IPCadapter instance;
public static IPCadapter getInstance()
{
Expand Down Expand Up @@ -68,7 +65,7 @@ protected virtual void OnTokenEvent(StartToken e)
public abstract void startWithToken(string uri);

// This method is for implementations that might be cancelable - such as DBUS.
public virtual bool Cancel()
public virtual async Task<bool> Cancel()
{
return true;
}
Expand Down
1 change: 1 addition & 0 deletions AmongUsCapture/IPC/Windows/IPCadapterRpcBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using SharedMemory;
using Mutex = System.Threading.Mutex;
using Process = System.Diagnostics.Process;
#pragma warning disable 4014

namespace AmongUsCapture.Windows
{
Expand Down
2 changes: 1 addition & 1 deletion AmongUsCapture/Memory/ProcessMemory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static ProcessMemory getInstance()
protected bool is64Bit;
public Process process;
public List<Module> modules;
public bool IsHooked { get; protected set; }
public bool IsHooked => process != null && !process.HasExited;
public abstract bool HookProcess(string name);
public abstract void LoadModules();
public abstract T Read<T>(IntPtr address, params int[] offsets) where T : unmanaged;
Expand Down
2 changes: 0 additions & 2 deletions AmongUsCapture/Memory/ProcessMemoryLinux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,6 @@ public override bool HookProcess(string name)
is64Bit = flag;

LoadModules();
IsHooked = true;

}

}
Expand Down
6 changes: 0 additions & 6 deletions AmongUsCapture/Memory/ProcessMemoryWindows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,6 @@ namespace AmongUsCapture
{
public class ProcessMemoryWindows : ProcessMemory
{
private static bool is64Bit;
public static Process process;
public static List<Module> modules;

public static bool IsHooked => process != null && !process.HasExited;

public override bool HookProcess(string name)
{
if (!IsHooked)
Expand Down
Loading

0 comments on commit b4af7a2

Please sign in to comment.