From 164430e9b4b9be213f4548fff0a430f11336ce49 Mon Sep 17 00:00:00 2001
From: Manuel Thalmann <m@nuth.ch>
Date: Sat, 15 Jul 2023 19:33:12 +0200
Subject: [PATCH] Try waiting for file download

---
 scripts/Windows/Scripts/BrowserAutomation.ps1 | 25 +++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/scripts/Windows/Scripts/BrowserAutomation.ps1 b/scripts/Windows/Scripts/BrowserAutomation.ps1
index 78ab4102..69288b55 100644
--- a/scripts/Windows/Scripts/BrowserAutomation.ps1
+++ b/scripts/Windows/Scripts/BrowserAutomation.ps1
@@ -24,7 +24,32 @@ function Start-AutomatedDownload() {
     $options.SetPreference("browser.download.folderList", 2);
     $options.SetPreference("browser.download.dir", $tempDir);
     # $options.AddArgument("--headless");
+
+    $downloadChecker = {
+        param()
+
+        foreach ($file in Get-ChildItem $tempDir) {
+            try {
+                $stream = [System.IO.File]::Open($file.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None);
+
+                if ($stream) {
+                    $stream.Close();
+                }
+
+                return $false;
+            }
+            catch  {
+                return $true;
+            }
+        }
+    }
+
     $browser = [OpenQA.Selenium.Firefox.FirefoxDriver]::new($options);
     $browser.Navigate().GoToUrl($url);
     $browser.FindElement([OpenQA.Selenium.By]::CssSelector("$buttonSelector")).Click();
+
+    while ($downloadChecker.Invoke()) {
+        Write-Information "Waiting for download to finish...";
+        Start-Sleep 1;
+    }
 }