Skip to content

Commit

Permalink
Merge pull request #6 from Nomi/dev
Browse files Browse the repository at this point in the history
v2.0.1

Minor changes, updates, additions, and refactoring.
  • Loading branch information
Nomi authored Feb 27, 2024
2 parents 0c5944e + 4ee08d5 commit 8dc63bc
Show file tree
Hide file tree
Showing 28 changed files with 516 additions and 218 deletions.
118 changes: 75 additions & 43 deletions Auxiliary/BrowserDiscoveryUtils.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
using AdvancedSharpAdbClient;
using AdvancedSharpAdbClient.Models;
using AdvancedSharpAdbClient.DeviceCommands;
using AdvancedSharpAdbClient.Receivers;
using ChromeDroid_TabMan.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ChromeDroid_TabMan.Auxiliary.ImportUtils;
using AdvancedSharpAdbClient.DeviceCommands;
using ChromeDroid_TabMan.Connection_and_Import;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Cryptography.X509Certificates;
using System.Reflection.PortableExecutable;
using System.IO.Pipes;
using ChromeDroid_TabMan.Auxiliary.Exceptions;

namespace ChromeDroid_TabMan.Auxiliary
{
Expand Down Expand Up @@ -38,62 +43,87 @@ public static List<string> GetDevToolsSockets(string adbPath)
client.ExecuteShellCommand(device, @"ss -a 2>/dev/null| grep devtools| cut -F 5", cOR);
string response = cOR.ToString();

return response.Split("\n").ToList();
List<string> result = response.Split("\n").Select(s => s.Replace("\r", "").Replace("\n", "").Replace("@", "")).ToList();
result.RemoveAll(s => (s == string.Empty));
return result;
}
public static async Task<List<string>> GetDevToolsSocketsNamesAsync(AdbConnection adbConnection)
{
AdbClient client = adbConnection.client;
DeviceData device = adbConnection.device;

ConsoleOutputReceiver cOR = new();
await client.ExecuteShellCommandAsync(device, @"ss -a 2>/dev/null| grep devtools| cut -F 5", cOR);
string response = cOR.ToString();

List<string> result = response.Split("\n").Select(s => s.Replace("\r", "").Replace("\n", "").Replace("@", "")).ToList();
result.RemoveAll(s => (s == string.Empty));
return result;
}

public static void VerifyExistingSockets(List<BrowserComboItem> browserComboItemsToVerify, List<string> devToolsSocketsFound, string adbPath) //remember that C# passes objects and collections of objects as references.
public static async Task VerifyExistingSocketsAsync(List<BrowserComboItem> browserComboItemsToVerify, List<string> devToolsSocketsFound, AdbConnection adbConnection) //remember that C# passes objects and collections of objects as references.
{
List<Task> runningTasks = new List<Task>();
for (int i = 0; i < browserComboItemsToVerify.Count; i++)
{
var browser = browserComboItemsToVerify[i];
var currBD = browser.BrowserDetails;

var socketFullName = browser.BrowserDetails.SocketNameFullOrPartial;
if ((!currBD.IsSocketNameFull && currBD.PackageName != null) || currBD.PackageName==ConfigHelper.ADB.Chrome_PackageName)//the || currBD.PackageName==ConfigHelper.ADB.Chrome_PackageName condition fixes the condition where one of the other chromium browsers somehow gets the name default devtools socket before chrome.
{
runningTasks.Add(verifyBrowserDevToolsSocketAsync(browser, devToolsSocketsFound, adbConnection));
}
await Task.WhenAll(runningTasks);
return; //Task.CompletedTask
}
private static async Task verifyBrowserDevToolsSocketAsync(BrowserComboItem browser, List<string> devToolsSocketsFound, AdbConnection adbConnection)
{
var currBD = browser.BrowserDetails;
var socketFullName = browser.BrowserDetails.Socket.SocketConnectionStr;
var socketNameOnly = browser.BrowserDetails.Socket.Name;
if ((!currBD.Socket.IsSocketNameComplete && currBD.PackageName != null) || currBD.PackageName == ConfigHelper.ADB.Chrome_PackageName)//the || currBD.PackageName==ConfigHelper.ADB.Chrome_PackageName condition fixes the condition where one of the other chromium browsers somehow gets the name default devtools socket before chrome.
{

try
{
socketFullName = currBD.SocketNameFullOrPartial + "_" + ImportUtils.GetChromiumBrowserPid(adbPath, currBD.PackageName, false);
}
catch (PidNotParsedException pidEx)
{ //This mostly means the browser is not running, so we can safely mark the browser's sockets as not found.
browser.BrowserDetails = new BrowserDetailsStruct(currBD.BrowserName, currBD.PackageName, currBD.SocketNameFullOrPartial, currBD.IsSocketNameFull, DiscoveryStateEnum.NotFound);
continue;
}
}
if (devToolsSocketsFound.Any(s => (socketFullName == "localabstract:" + s.Replace("\r", "").Replace("\n", "").Replace("@", ""))))
try
{
DiscoveryStateEnum discoveryState = DiscoveryStateEnum.Verified;
if (currBD.PackageName == ConfigHelper.ADB.Chrome_PackageName && socketFullName != ConfigHelper.ADB.Chrome_ForwardParameter_Remote)
discoveryState = DiscoveryStateEnum.RediscoveredAndFixed;
else if (!currBD.IsSocketNameFull)
discoveryState = DiscoveryStateEnum.RediscoveredAndFilledRestOfTheSocket;
browser.BrowserDetails = new BrowserDetailsStruct(currBD.BrowserName, currBD.PackageName, socketFullName, true, discoveryState);
devToolsSocketsFound.RemoveAll(s => (socketFullName == "localabstract:" + s.Replace("\r", "").Replace("\n", "").Replace("@", "")));
string pid = (await ImportUtils.GetChromiumBrowserPidAsync(adbConnection, currBD.PackageName, false));
socketNameOnly += "_" + pid;
socketFullName += "_" + pid;
}
else if(currBD.PackageName==ConfigHelper.ADB.Chrome_PackageName && devToolsSocketsFound.Any(s=>s==ConfigHelper.ADB.Chrome_ForwardParameter_Remote))
{
browser.BrowserDetails = new BrowserDetailsStruct(currBD.BrowserName, currBD.PackageName, ConfigHelper.ADB.Chrome_ForwardParameter_Remote, true, DiscoveryStateEnum.Verified);
//not removing this from devTools so that it can be verified later in the next stage.
}
else
{
browser.BrowserDetails = new BrowserDetailsStruct(currBD.BrowserName, currBD.PackageName, currBD.SocketNameFullOrPartial, currBD.IsSocketNameFull, DiscoveryStateEnum.NotFound);
catch (PidNotParsedException pidEx)
{ //This mostly means the browser is not running, so we can safely mark the browser's sockets as not found.
browser.BrowserDetails.DiscoveryState = DiscoveryStateEnum.NotFound;
return;
}
}
if (devToolsSocketsFound.Any(s => (socketNameOnly == s)))
{
DiscoveryStateEnum discoveryState = DiscoveryStateEnum.Verified;
if (currBD.PackageName == ConfigHelper.ADB.Chrome_PackageName && socketFullName != ConfigHelper.ADB.Chrome_ForwardParameter_Remote)
discoveryState = DiscoveryStateEnum.RediscoveredAndFixed;
else if (!currBD.Socket.IsSocketNameComplete)
discoveryState = DiscoveryStateEnum.RediscoveredAndFilledRestOfTheSocket;

browser.BrowserDetails.Socket.Name = socketNameOnly;
browser.BrowserDetails.Socket.IsSocketNameComplete = true;
browser.BrowserDetails.DiscoveryState = discoveryState;
devToolsSocketsFound.RemoveAll(s => (socketNameOnly == s));
}
else if (currBD.PackageName == ConfigHelper.ADB.Chrome_PackageName && devToolsSocketsFound.Any(s => s == ConfigHelper.ADB.Chrome_DevToolRemote_String))
{
browser.BrowserDetails.DiscoveryState = DiscoveryStateEnum.Verified;
//not removing this from devTools so that it can be verified later in the next stage.
}
else
{
browser.BrowserDetails.DiscoveryState = DiscoveryStateEnum.NotFound;
}
}

//The following cannot be async!
public static void DiscoverNewSocketsAndOrFixKnownBrowsersWithUnexpectedSocketNames(List<BrowserComboItem> existingBrowserComboList, List<string> devToolsSocketsFound, string adbPath_ProvideIfNewBrowserDetailsNeeded=null) //remember that C# passes objects and collections of objects as references.
{
string adbPath = adbPath_ProvideIfNewBrowserDetailsNeeded;
HashSet<string> packageNameOfBrowsersThatCanBeFixed = existingBrowserComboList.Where(b => b.BrowserDetails.PackageName.Contains(ConfigHelper.ADB.EdgeAndBraveAndChrome_Base_ForwardParameterRemote__MissingPidAtEnd)).Select(b=>b.BrowserDetails.PackageName).ToHashSet();
foreach (string currConnSocket in devToolsSocketsFound)
foreach (string currSocketName in devToolsSocketsFound)
{
if (currConnSocket == string.Empty)
continue;
string nSocket = currConnSocket.Replace("\r", "").Replace("\n", "").Replace("@", "");
string currSocketFull = "localabstract:" + nSocket;
string currSocketFull = ConfigHelper.ADB.LocalAbstractString + ":" + currSocketName;
string browserName = currSocketFull;
string packageName = null;
if(adbPath!=null) //this means that we are supposed to fill in the details for each newly discovered device.
Expand Down Expand Up @@ -124,19 +154,21 @@ public static void DiscoverNewSocketsAndOrFixKnownBrowsersWithUnexpectedSocketNa
}
//}

existingBrowserComboList[preexistingIndex] = new BrowserComboItem(currBD.BrowserName, currBD.PackageName, currSocketFull, true, discoveryState);
existingBrowserComboList[preexistingIndex].BrowserDetails.DiscoveryState = discoveryState;
return;
}
}
BrowserComboItem browser = new BrowserComboItem(browserName, packageName, currSocketFull, true, DiscoveryStateEnum.Discovered);
existingBrowserComboList.Add(browser);
SocketInfo socket = new SocketInfo(currSocketFull, true, true);
BrowserInfo browser = new BrowserInfo(browserName, packageName, socket, DiscoveryStateEnum.Discovered);
BrowserComboItem browserCI = new BrowserComboItem(browser);
existingBrowserComboList.Add(browserCI);
}
}


public static BrowserJsonVersionDTO GetBrowserDetails(string adbPath,string forwardParameter_Remote)
{
IAdbConnector adbConnector = new DiscoveredSocketOnlyAdbConnector(adbPath, forwardParameter_Remote);
IChromiumDevToolsConnector adbConnector = new DiscoveredSocketOnlyDevToolsConnector(adbPath, forwardParameter_Remote);
adbConnector.StartAdbJsonListServer();
HttpClient httpClient = new();
BrowserJsonVersionDTO response = httpClient.GetFromJsonAsync<BrowserJsonVersionDTO>(ConfigHelper.ADB.BrowserJsonVersionURL).Result;
Expand Down
10 changes: 6 additions & 4 deletions Auxiliary/ConfigHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,12 @@ public static class ADB
public static string TabsJsonListURL => BaseLocalForwardedURL + TabListEndpoint;
public static string BrowserVersionEndpoint => "/json/version";
public static string BrowserJsonVersionURL => BaseLocalForwardedURL + BrowserVersionEndpoint;
public static string Chrome_ForwardParameter_Remote => "localabstract:chrome_devtools_remote";
public static string SamsungInternet_ForwardParameter_Remote => "localabstract:Terrace_devtools_remote";
public static string Opera_ForwardParameter_Remote => "localabstract:com.opera.browser.devtools";
private static string EdgeAndBrave_ExceptionMessage_For_ForwardParameter_Remote => "For Edge and Brave, the ForwardParameter_Remote is the concatenation of \"localabstract:chrome_devtools_remote_\" with the process ID of the process of the browser instance at that time (can be found using pidof command).";
public static string LocalAbstractString => "localabstract";
public static string Chrome_DevToolRemote_String => "chrome_devtools_remote";
public static string Chrome_ForwardParameter_Remote => LocalAbstractString+":"+Chrome_DevToolRemote_String;
public static string SamsungInternet_ForwardParameter_Remote => LocalAbstractString + ":" + "Terrace_devtools_remote";
public static string Opera_ForwardParameter_Remote => LocalAbstractString + ":" + "com.opera.browser.devtools";
private static string EdgeAndBrave_ExceptionMessage_For_ForwardParameter_Remote => throw new Exception("For Edge and Brave, the ForwardParameter_Remote is the concatenation of \"localabstract:chrome_devtools_remote_\" with the process ID of the process of the browser instance at that time (can be found using pidof command).");
//public static string Edge_ForwardParameter_Remote => throw new Exception(EdgeAndBrave_ExceptionMessage_For_ForwardParameter_Remote);
//public static string Brave_ForwardParameter_Remote => throw new Exception(EdgeAndBrave_ExceptionMessage_For_ForwardParameter_Remote);
public static string EdgeAndBraveAndChrome_Base_ForwardParameterRemote__MissingPidAtEnd => Chrome_ForwardParameter_Remote;
Expand Down
13 changes: 13 additions & 0 deletions Auxiliary/Exceptions/AdbDeviceNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChromeDroid_TabMan.Auxiliary.Exceptions
{
public class AdbDeviceNotFoundException : Exception
{
public AdbDeviceNotFoundException() : base("ERROR: ADB device either is not connected or was not found.") { }
}
}
28 changes: 28 additions & 0 deletions Auxiliary/Exceptions/GlobalUnhandledExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.Threading;
using System.Windows.Forms;

public static class GlobalUnhandledExceptionHandler
{
public static void Initialize()
{
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}

private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
Exception ex = e.Exception;
MessageBox.Show(ex.Message, $"Error: (unhandled exception: {ex.GetType().Name})", MessageBoxButtons.OK, MessageBoxIcon.Error);
//write stack trace somewhere? and/or add logging?
}

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
if (ex != null)
{
MessageBox.Show("An unexpected error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
16 changes: 16 additions & 0 deletions Auxiliary/Exceptions/PidNotParsedException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChromeDroid_TabMan.Auxiliary.Exceptions
{
public class PidNotParsedException : Exception
{
public PidNotParsedException(string message = "PID could not be found or parsed. One possibility is that the process may not be running.") : base(message)
{

}
}
}
Loading

0 comments on commit 8dc63bc

Please sign in to comment.