Skip to content

Commit

Permalink
Add auto updater for web driver
Browse files Browse the repository at this point in the history
  • Loading branch information
NoxModule committed Mar 19, 2022
1 parent 013176e commit 185fdc6
Show file tree
Hide file tree
Showing 6 changed files with 152 additions and 44 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
bin/
obj/
Driver_Notes/
User Data/

*.exe
*.log
*.zip
6 changes: 3 additions & 3 deletions PlexAutoIntroSkip.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
<Configuration>Release</Configuration>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<PublishTrimmed>true</PublishTrimmed>
<SelfContained>true</SelfContained>
<PublishSingleFile>true</PublishSingleFile>
<PublishReadyToRun>true</PublishReadyToRun>
<PublishReadyToRunShowWarnings>true</PublishReadyToRunShowWarnings>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<ApplicationIcon>PlexIcon.ico</ApplicationIcon>
</PropertyGroup>
Expand Down
83 changes: 45 additions & 38 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,11 @@

namespace PlexAutoIntroSkip
{
/// <summary>
/// Program entry point.
/// </summary>
public class Program
{
public class ProgramOptions
{
[Option('d', "debug", Required = false,
HelpText = "Show console window.")]
public bool ShowConsoleWindow { get; set; }

[Option('w', "wait-time", Required = false, Default = 2500,
HelpText = "Time to wait after Skip Button becomes visible before clicking.")]
public int SkipButtonWaitTime { get; set; }

[Value(0, MetaName = "plex-url", HelpText = "Plex URL to use.")]
public string PlexUrl { get; set; }
}

/// <summary>
/// Sets the specified window's show state.
/// </summary>
Expand All @@ -41,7 +30,7 @@ public class ProgramOptions
/// If the window was previously hidden, the return value is zero.
/// </returns>
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

/// <summary>
/// Program entry point.
Expand All @@ -50,18 +39,13 @@ public class ProgramOptions
public static void Main(string[] args)
{
var options = GetProgramOptions(args);
var hWnd = Process.GetCurrentProcess().MainWindowHandle;
var edgeProcessName = "msedge";

// Called using own process window?
if (options.ShowConsoleWindow == false && hWnd.ToInt32() != 0)
{
// Hide console application's console window.
ShowWindow(hWnd, 0);
}
HandleConsoleWindow(options.ShowConsoleWindow);

var edgeOptions = new EdgeOptions();
edgeOptions.UseChromium = true;
var edgeOptions = new EdgeOptions
{
UseChromium = true,
};

// Disable "Chrome is being controlled by automated test software" infobar.
edgeOptions.AddExcludedArgument("enable-automation");
Expand All @@ -72,8 +56,22 @@ public static void Main(string[] args)
"profile-directory=Profile 1",
$"app={options.PlexUrl}");

var edgeProcessName = "msedge";
var edgeProcessIds = Process.GetProcessesByName(edgeProcessName).Select(p => p.Id);
var service = EdgeDriverService.CreateDefaultService();

EdgeDriverService service;
if (options.ManualHandleWebDriver)
{
service = EdgeDriverService.CreateDefaultService();
}
else
{
WebDriverManager.AutoUpdate();

service = EdgeDriverService.CreateDefaultService(
WebDriverManager.MsEdgeDriverDirectoryName, WebDriverManager.MsEdgeDriverFileName);
}

var driver = new EdgeDriver(service, edgeOptions);
var browserProcessId = Process.GetProcessesByName(edgeProcessName).Select(p => p.Id)
.Except(edgeProcessIds)
Expand All @@ -94,6 +92,17 @@ public static void Main(string[] args)
Process.GetProcessById(service.ProcessId).Kill();
}

private static void HandleConsoleWindow(bool showConsoleWindow)
{
var hWnd = Process.GetCurrentProcess().MainWindowHandle;

// Hide console window and called using own process window?
if (showConsoleWindow == false && hWnd.ToInt32() != 0)
{
ShowWindow(hWnd, 0);
}
}

/// <summary>
/// Run main program loop.
/// </summary>
Expand Down Expand Up @@ -163,21 +172,19 @@ private static ProgramOptions GetProgramOptions(string[] args)
/// <param name="exception">Root <see name="Exception"/>.</param>
private static void LogException(Exception exception)
{
using (var writer = new StreamWriter("error.log", append: true))
using var writer = new StreamWriter("error.log", append: true);
writer.WriteLine("--------------------------------------------------");
writer.WriteLine($"[{DateTime.Now}]");
writer.WriteLine();

while (exception != null)
{
writer.WriteLine("--------------------------------------------------");
writer.WriteLine($"[{DateTime.Now}]");
writer.WriteLine(exception.GetType().FullName);
writer.WriteLine(exception.Message);
writer.WriteLine(exception.StackTrace);
writer.WriteLine();

while (exception != null)
{
writer.WriteLine(exception.GetType().FullName);
writer.WriteLine(exception.Message);
writer.WriteLine(exception.StackTrace);
writer.WriteLine();

exception = exception.InnerException;
}
exception = exception.InnerException;
}
}

Expand Down
20 changes: 20 additions & 0 deletions ProgramOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using CommandLine;

namespace PlexAutoIntroSkip
{
public class ProgramOptions
{
[Option('d', "debug", Required = false, HelpText = "Show console window.")]
public bool ShowConsoleWindow { get; set; }

[Option('m', "manual-driver", Required = false, HelpText = "Manually handle MS Edge Web Driver.")]
public bool ManualHandleWebDriver { get; set; }

[Option('w', "wait-time", Required = false, Default = 2500,
HelpText = "Time to wait after Skip Button becomes visible before clicking.")]
public int SkipButtonWaitTime { get; set; }

[Value(0, MetaName = "plex-url", HelpText = "Plex URL to use.")]
public string PlexUrl { get; set; }
}
}
11 changes: 8 additions & 3 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,20 @@ Plex has an great feature that allows users to [Skip TV Show Intros](https://sup

## How to Install

1. Download latest appropriate _Stable Channel_ release of [Microsoft Edge Driver](https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/).
1. Extract `msedgedriver.exe` from the downloaded ZIP archive and place it into your environment's PATH.
* If you are not sure where to place it, place it in the `C:\Windows\System32`.
1. Download latest [Plex Auto Intro Skip Release](https://github.com/OpenNOX/PlexAutoIntroSkip/releases) and place it in a location it will be run from.
1. Right-click on `PlexAutoIntroSkip.exe`, select "Create shortcut", right-click on newly created shortcut, and select "Properties".
1. In the shortcut's properties window navigate to the end of "Target" textbox and add a space followed by "`{URL_TO_PLEX_SERVER}`" with double-quotes.
* Finished example: `C:\bins\PlexAutoIntroSkip\PlexAutoIntroSkip.exe "https://plex.server/"`
1. Click the "Ok" button, and move (or pin) the shortcut to the desired location to launch from.

## Options

* `-d`, `--debug` **:** Show console window.
* `-m`, `--manual-driver` **:** Manually handle MS Edge Web Driver.
* If manually handling web driver the executable will need to be in environment's PATH or next to the `PlexAutoIntroSkip` executable.
* `-w`, `--wait-time` **:** Time to wait, in milliseconds, after Skip Button becomes visible before clicking.
* **Default:** 2500

## Notes

* On initial launch you will be asked to sign in to Plex, this is because the program is using a different user data directory than default for the instance of Microsoft Edge.
Expand Down
73 changes: 73 additions & 0 deletions WebDriverManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text.RegularExpressions;

namespace PlexAutoIntroSkip
{
public static class WebDriverManager
{
public static readonly string MsEdgeDriverFilePath = Path.GetFullPath(@"./edgedriver_win64/msedgedriver.exe");

public static readonly string MsEdgeDriverDirectoryName = "edgedriver_win64";

public static readonly string MsEdgeDriverFileName = "msedgedriver.exe";

private static readonly string _stableChannelLatestVersionAddress = "https://msedgedriver.azureedge.net/LATEST_STABLE";

private static readonly string _stableChannelAddress = "https://msedgedriver.azureedge.net/<<VERSION>>/edgedriver_win64.zip";

private static readonly Regex _msEdgeDriverVersionRegEx = new(@"(\d+\.\d+\.\d+)");

public static void AutoUpdate()
{
var webClient = new WebClient();
var httpStream = webClient.OpenRead(_stableChannelLatestVersionAddress);
var streamReader = new StreamReader(httpStream);
var latestVersion = streamReader.ReadLine();

streamReader.Close();
httpStream.Close();

var currentVersion = string.Empty;
if (File.Exists(MsEdgeDriverFilePath))
{
currentVersion = GetMsEdgeDriverVersion(MsEdgeDriverFilePath);
}

if (currentVersion != _msEdgeDriverVersionRegEx.Match(latestVersion).Value)
{
var downloadFileName = $"./{MsEdgeDriverDirectoryName}.zip";

webClient.DownloadFile(_stableChannelAddress.Replace("<<VERSION>>", latestVersion), downloadFileName);
ZipFile.ExtractToDirectory(downloadFileName, MsEdgeDriverDirectoryName, overwriteFiles: true);
}

webClient.Dispose();
}

private static string GetMsEdgeDriverVersion(string msEdgeDriverPath)
{
var msEdgeDriver = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = msEdgeDriverPath,
Arguments = "--version",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
}
};

msEdgeDriver.Start();
while (msEdgeDriver.StandardOutput.EndOfStream == false)
{
return _msEdgeDriverVersionRegEx.Match(msEdgeDriver.StandardOutput.ReadLine()).Value;
}

return string.Empty;
}
}
}

0 comments on commit 185fdc6

Please sign in to comment.