diff --git a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignIn.java b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignIn.java index e29c3f299..fce3e1b23 100644 --- a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignIn.java +++ b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignIn.java @@ -18,12 +18,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; +import java.util.HexFormat; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -58,12 +60,35 @@ public final class BattleNetSignIn { static final long SIGN_IN_TIMEOUT_SECONDS = 120; /** How long a canceled renewal keeps closing the client it asked the app for, which may still be on its way. */ static final long LATE_GAME_SECONDS = 30; + /** Another holder renews (up to {@value #TIMEOUT_SECONDS} s) and waits for its client to sign in; outwait both. */ + static final long GATE_WAIT_SECONDS = TIMEOUT_SECONDS + SIGN_IN_TIMEOUT_SECONDS + 30; + + /** + * Another tool has held the renewal lock for longer than a renewal and a sign-in take. Not a reason to launch + * without it: that launch could spend the token the other tool's client has not read yet. + */ + static final class LockBusyException extends IOException { + LockBusyException(String message) { + super(message); + } + } + + /** What Run Map calls to renew; see {@link RunMap#renewOrRefuse}. */ + @FunctionalInterface + interface Renewer { + Renewal renew(Runnable onWait) throws IOException; + } private static final Pattern REG_BINARY = Pattern.compile("^\\s*(\\S+)\\s+REG_BINARY\\s+([0-9A-Fa-f]*)\\s*$", Pattern.MULTILINE); private final Path config; private final Path gateDir; private final Path launcher; + /** A renewal for {@code config} whose launcher is never started; for tests that only touch the lock. */ + static BattleNetSignIn forTest(Path config, Path gateDir) { + return new BattleNetSignIn(config, gateDir, Path.of("Battle.net.exe")); + } + private BattleNetSignIn(Path config, Path gateDir, Path launcher) { this.config = config; this.gateDir = gateDir; @@ -117,7 +142,16 @@ boolean isRunning() { * {@link Renewal#releaseWhenSignedIn()}, or {@link Renewal#close()} if the launch fails */ Renewal renew() throws IOException { - ServerSocket gate = acquireGate(); + return renew(GATE_WAIT_SECONDS, () -> { }); + } + + /** @param onWait called once if another launch holds the lock and this one has to wait for it */ + Renewal renew(Runnable onWait) throws IOException { + return renew(GATE_WAIT_SECONDS, onWait); + } + + Renewal renew(long gateWaitSeconds, Runnable onWait) throws IOException { + ServerSocket gate = acquireGate(gateWaitSeconds, onWait); Set seen = new HashSet<>(); boolean[] asked = {false}; try { @@ -220,6 +254,9 @@ private String renewLocked(Set seen, boolean[] asked) throws IOException { seen.add(game.pid()); } Optional before = readBinary(LAUNCH_KEY, "WEB_TOKEN"); + // Asked to start the game, the app creates a window in front, and shows it again as the map's client signs + // in; the watcher hides it as it is created. + watchLauncherWindow(); long start = System.nanoTime(); long askedAt = Long.MIN_VALUE; String token = null; @@ -259,6 +296,74 @@ private String renewLocked(Set seen, boolean[] asked) throws IOException { return token; } + /** A copy of the wc3-e2e-harness {@code node/src/runner/battlenet-window.ps1}; keep them equal. */ + static final String WINDOW_SCRIPT = "battlenet-window.ps1"; + /** The watcher's limit without a client: every request the renewal may send, then a launch and a slow sign-in. */ + static final long WINDOW_WATCH_SECONDS = TIMEOUT_SECONDS + 150; + private static final long WINDOW_READY_SECONDS = 3; + + /** + * The command that runs {@link #WINDOW_SCRIPT} with {@code arguments}, from a copy in {@code dir} named by its + * content (a file, not -EncodedCommand: encoded, the script is close to Windows' 32,767-character command line + * limit). Null when the script cannot be provided. + */ + static List windowWatcherCommand(List arguments, Path dir) { + try (var in = BattleNetSignIn.class.getClassLoader().getResourceAsStream(WINDOW_SCRIPT)) { + if (in == null) return null; + byte[] script = in.readAllBytes(); + String hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(script), 0, 6); + Path file = dir.resolve("wurst-battlenet-window-" + hash + ".ps1"); + if (!Files.isRegularFile(file) || !Arrays.equals(Files.readAllBytes(file), script)) Files.write(file, script); + List command = new ArrayList<>(List.of("powershell.exe", "-NoProfile", "-NonInteractive", + "-ExecutionPolicy", "Bypass", "-File", file.toString())); + command.addAll(arguments); + return command; + } catch (IOException | NoSuchAlgorithmException ex) { + WLogger.warning("Could not prepare the Battle.net window watcher: " + ex.getMessage()); + return null; + } + } + + /** + * Starts the app window watcher and waits until it has noted the windows already open (at most + * {@value #WINDOW_READY_SECONDS} s). It then runs on its own: it ends a minute after the map's client appears, past + * its sign-in, or after {@link #WINDOW_WATCH_SECONDS}. Best effort: a watcher that does not start only means the + * app's window may show. Run Map focuses its client itself ({@link BattleNetLaunchWindows}), so the watcher does not. + */ + private static void watchLauncherWindow() { + List command = windowWatcherCommand(List.of("-Seconds", String.valueOf(WINDOW_WATCH_SECONDS)), + Path.of(System.getProperty("java.io.tmpdir"))); + if (command == null) return; + Process process; + try { + process = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + } catch (IOException ex) { + WLogger.warning("Could not start the Battle.net window watcher: " + ex.getMessage()); + return; + } + CountDownLatch ready = new CountDownLatch(1); + Thread reader = new Thread(() -> { + // The watcher prints nothing after "ready", so its output can be let go then. + try (var output = process.inputReader()) { + String line; + while ((line = output.readLine()) != null) { + if (line.strip().equals("ready")) break; + } + } catch (IOException ignored) { + // A watcher that stopped early only means the app's window may show. + } finally { + ready.countDown(); + } + }, "Battle.net window watcher"); + reader.setDaemon(true); + reader.start(); + try { + ready.await(WINDOW_READY_SECONDS, TimeUnit.SECONDS); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + private static List games() { return ProcessHandle.allProcesses() .filter(process -> command(process).filter(path -> named(path, GAME)).isPresent()).toList(); @@ -324,9 +429,10 @@ static int gatePort(Path config) { } } - private ServerSocket acquireGate() throws IOException { + private ServerSocket acquireGate(long waitSeconds, Runnable onWait) throws IOException { Files.createDirectories(gateDir); - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(waitSeconds); + boolean waiting = false; while (true) { ServerSocket socket = new ServerSocket(); try { @@ -335,7 +441,16 @@ private ServerSocket acquireGate() throws IOException { return socket; } catch (BindException ex) { socket.close(); - if (System.nanoTime() >= deadline) throw new IOException("Another Warcraft III test is using Battle.net.", ex); + if (!waiting) { + waiting = true; + onWait.run(); + } + if (System.nanoTime() >= deadline) { + LockBusyException busy = new LockBusyException( + "Another Warcraft III launch has held the Battle.net sign-in for over " + waitSeconds + " s."); + busy.initCause(ex); + throw busy; + } pause(250); } catch (IOException ex) { socket.close(); diff --git a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java index 72bdd6b0a..4527e7844 100644 --- a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java +++ b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java @@ -296,7 +296,8 @@ private BattleNetSignIn.Renewal renewBattleNetSignIn(WurstGui gui, Path executab if (battleNet.isPresent() && (required || battleNet.get().isRunning())) { try { gui.sendProgress("Renewing the Warcraft III sign-in from Battle.net..."); - return battleNet.get().renew(); + return renewOrRefuse(battleNet.get()::renew, + () -> gui.sendProgress("Another Warcraft III launch is signing in; waiting until it has...")); } catch (IOException e) { WLogger.warning("Could not renew the Warcraft III sign-in from Battle.net: " + e.getMessage()); problem = e.getMessage(); @@ -312,6 +313,19 @@ private BattleNetSignIn.Renewal renewBattleNetSignIn(WurstGui gui, Path executab } } + /** + * Renews the sign-in, but never lets a busy lock pass as "could not renew": in "auto" that would launch without the + * lock, and that launch could spend the token another tool's client has not read yet. A busy lock fails the run in + * every mode; other failures are thrown on for the caller's fallback. + */ + static BattleNetSignIn.Renewal renewOrRefuse(BattleNetSignIn.Renewer renewer, Runnable onWait) throws IOException { + try { + return renewer.renew(onWait); + } catch (BattleNetSignIn.LockBusyException e) { + throw new RequestFailedException(MessageType.Error, e.getMessage() + " Run the map again once it has signed in."); + } + } + static String askBattleNet(LanguageClient client, String message) { ShowMessageRequestParams prompt = new ShowMessageRequestParams(); prompt.setType(MessageType.Warning); diff --git a/de.peeeq.wurstscript/src/main/resources/battlenet-window.ps1 b/de.peeeq.wurstscript/src/main/resources/battlenet-window.ps1 new file mode 100644 index 000000000..867886b9d --- /dev/null +++ b/de.peeeq.wurstscript/src/main/resources/battlenet-window.ps1 @@ -0,0 +1,235 @@ +# Keeps the Battle.net app's window out of sight while a sign-in renewal asks it to start Warcraft III. +# +# Asked to start a game, the app creates its window and shows it in front, and depending on its "when I launch a game" +# setting leaves it there. Started just before the renewal, this hooks window creation: each new top-level app window +# is moved off-screen as it is created, so it is shown out of sight, and then minimized without being activated. Its +# restore position is set back to where the app put it, so the user's own next Restore opens it normally. An app window +# that was already open is minimized too if it takes the foreground, and left alone otherwise. With -FocusGame it brings +# the map's Warcraft III client to the front once that has a window: a client that started after this script and not +# from the app, so never the user's own game or the renewal's short-lived one. +# +# The app shows its window again as the map's client signs in, so the watcher ends $GameSeconds after that client +# (one that started after this script and not from the app) appears, or at $Seconds if none does. Until that client +# appears, a new crash reporter (BlizzardError.exe) of the renewal's closed client is closed; any other is left alone. +# +# Prints "ready" once it has noted the windows already open, so the caller can ask the app only then; with -Log also +# one line per action. WurstSetup embeds a copy; keep it self-contained. +param([int]$Seconds = 20, [int]$GameSeconds = 60, [switch]$FocusGame, [switch]$Log) +$ErrorActionPreference = "Stop" +Add-Type @" +using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; +public static class BattleNetWindow { + delegate bool EnumProc(IntPtr h, IntPtr p); + delegate void WinEventProc(IntPtr hook, uint ev, IntPtr hwnd, int idObject, int idChild, uint thread, uint time); + [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc f, IntPtr p); + [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h); + [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h); + [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h, uint cmd); + [DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr h, uint flags); + [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int cmd); + [DllImport("user32.dll")] static extern bool ShowWindowAsync(IntPtr h, int cmd); + [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags); + [DllImport("user32.dll")] static extern bool GetWindowPlacement(IntPtr h, ref WINDOWPLACEMENT p); + [DllImport("user32.dll")] static extern bool SetWindowPlacement(IntPtr h, ref WINDOWPLACEMENT p); + [DllImport("user32.dll")] static extern IntPtr SetWinEventHook(uint min, uint max, IntPtr mod, WinEventProc proc, uint pid, uint tid, uint flags); + [DllImport("user32.dll")] static extern bool UnhookWinEvent(IntPtr hook); + [DllImport("user32.dll")] static extern uint MsgWaitForMultipleObjects(uint n, IntPtr[] h, bool all, uint ms, uint mask); + [DllImport("user32.dll")] static extern bool PeekMessage(out MSG m, IntPtr h, uint min, uint max, uint remove); + [DllImport("user32.dll")] static extern bool TranslateMessage(ref MSG m); + [DllImport("user32.dll")] static extern IntPtr DispatchMessage(ref MSG m); + [DllImport("kernel32.dll")] static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint pid); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool Process32FirstW(IntPtr snap, ref PROCESSENTRY32 e); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool Process32NextW(IntPtr snap, ref PROCESSENTRY32 e); + [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h); + [StructLayout(LayoutKind.Sequential)] struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] struct POINT { public int X, Y; } + [StructLayout(LayoutKind.Sequential)] struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public POINT pt; } + [StructLayout(LayoutKind.Sequential)] struct WINDOWPLACEMENT { public int length, flags, showCmd; public POINT min, max; public RECT normal; } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct PROCESSENTRY32 { + public uint dwSize, cntUsage, th32ProcessID; public IntPtr th32DefaultHeapID; public uint th32ModuleID, cntThreads, + th32ParentProcessID; public int pcPriClassBase; public uint dwFlags; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szExeFile; } + + const uint EVENT_CREATE = 0x8000, EVENT_SHOW = 0x8002, EVENT_LOCATION = 0x800B; + const uint SWP_MOVE_ONLY = 0x0001 | 0x0004 | 0x0010; // NOSIZE | NOZORDER | NOACTIVATE + const int OFF_SCREEN = -32000; + static readonly Stopwatch watch = new Stopwatch(); + static readonly Dictionary moved = new Dictionary(); + static readonly HashSet handled = new HashSet(); + static HashSet background = new HashSet(); + static HashSet appPids = new HashSet(); + static readonly HashSet notOurGame = new HashSet(); + static readonly HashSet oldReporters = new HashSet(); + static readonly HashSet earlierGames = new HashSet(); + static readonly HashSet renewalClients = new HashSet(); + static bool log; + static WinEventProc callback; + + static void Note(string s) { if (log) Console.WriteLine("{0} {1:N2}", s, watch.Elapsed.TotalSeconds); } + + static Dictionary Processes() { + var all = new Dictionary(); + IntPtr snap = CreateToolhelp32Snapshot(2, 0); + if (snap == new IntPtr(-1)) return all; + try { + var e = new PROCESSENTRY32(); e.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)); + for (bool ok = Process32FirstW(snap, ref e); ok; ok = Process32NextW(snap, ref e)) all[e.th32ProcessID] = e; + } finally { CloseHandle(snap); } + return all; + } + + static HashSet Pids(Dictionary all, string exe) { + var pids = new HashSet(); + foreach (var e in all.Values) if (string.Equals(e.szExeFile, exe, StringComparison.OrdinalIgnoreCase)) pids.Add(e.th32ProcessID); + return pids; + } + + // Visible, not minimized, unowned top-level windows of the given processes. + static List Shown(HashSet pids) { + var found = new List(); + EnumWindows((h, p) => { + uint pid; GetWindowThreadProcessId(h, out pid); + if (pids.Contains(pid) && IsWindowVisible(h) && !IsIconic(h) && GetWindow(h, 4) == IntPtr.Zero) found.Add(h); + return true; + }, IntPtr.Zero); + return found; + } + + static bool AppWindow(IntPtr h) { + uint pid; GetWindowThreadProcessId(h, out pid); + return appPids.Contains(pid) && GetAncestor(h, 2) == h && GetWindow(h, 4) == IntPtr.Zero; + } + + // Minimizes without activating; the window holding the foreground is minimized normally, which hands it on. + static void Minimize(IntPtr h, string why) { + bool foreground = GetForegroundWindow() == h; + ShowWindow(h, foreground ? 6 : 7); + handled.Add(h); + RECT original; + if (moved.TryGetValue(h, out original) && original.Right > original.Left) { + var p = new WINDOWPLACEMENT(); p.length = Marshal.SizeOf(p); + if (GetWindowPlacement(h, ref p)) { p.normal = original; p.showCmd = 7; SetWindowPlacement(h, ref p); } + } + Note("minimized " + why); + } + + static void OnEvent(IntPtr hook, uint ev, IntPtr h, int idObject, int idChild, uint thread, uint time) { + if (idObject != 0 || idChild != 0 || h == IntPtr.Zero || !AppWindow(h)) return; + RECT r; GetWindowRect(h, out r); + bool onScreen = r.Left > OFF_SCREEN / 2; + if (ev == EVENT_CREATE) { + if (!moved.ContainsKey(h)) { + moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); + } + return; + } + if (!IsWindowVisible(h)) { + // Not shown yet: the app may put it back where it last was; keep it off-screen and remember that as its place. + if (ev == EVENT_LOCATION && moved.ContainsKey(h) && !handled.Contains(h) && onScreen) { + moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); + } + return; + } + if (IsIconic(h)) return; + // Shown, or restored, in the open: unless it is a window the user had open in the background, move it out of + // sight at once and minimize it. Its restore position stays the one the app first gave it. + if (background.Contains(h) && GetForegroundWindow() != h) return; + if (onScreen) { + if (!moved.ContainsKey(h)) moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); + } + Minimize(h, ev == EVENT_SHOW ? "shown window" : "restored window"); + } + + public static void Prepare(bool logActions) { + log = logActions; + var all = Processes(); + appPids = Pids(all, "Battle.net.exe"); + foreach (uint pid in Pids(all, "Warcraft III.exe")) { notOurGame.Add(pid); earlierGames.Add(pid); } + foreach (uint pid in Pids(all, "BlizzardError.exe")) oldReporters.Add(pid); + IntPtr foreground = GetForegroundWindow(); + background = new HashSet(Shown(appPids)); + background.Remove(foreground); + } + + public static void Run(int seconds, int gameSeconds, bool focusGame) { + watch.Start(); + callback = OnEvent; + IntPtr hook = SetWinEventHook(EVENT_CREATE, EVENT_LOCATION, IntPtr.Zero, callback, 0, 0, 0); + bool focused = !focusGame; + long lastScan = -1000; + double gameSeenAt = -1; + try { + // The app shows its window again as the map's client signs in, so watch until that client has run a while. + while (watch.Elapsed.TotalSeconds < seconds && (gameSeenAt < 0 || watch.Elapsed.TotalSeconds - gameSeenAt < gameSeconds)) { + MsgWaitForMultipleObjects(0, null, false, 25, 0x04FF); + MSG m; + while (PeekMessage(out m, IntPtr.Zero, 0, 0, 1)) { TranslateMessage(ref m); DispatchMessage(ref m); } + if (watch.ElapsedMilliseconds - lastScan < 50) continue; + lastScan = watch.ElapsedMilliseconds; + var all = Processes(); + appPids = Pids(all, "Battle.net.exe"); + IntPtr foreground = GetForegroundWindow(); + // An app window that was open already, or one the hook missed: minimize it if it is in the way. + foreach (IntPtr h in Shown(appPids)) { + if (background.Contains(h) && h != foreground) continue; + Minimize(h, "shown window"); + } + var ours = new HashSet(); + foreach (uint pid in Pids(all, "Warcraft III.exe")) { + if (notOurGame.Contains(pid)) continue; + PROCESSENTRY32 e; PROCESSENTRY32 parent; + if (all.TryGetValue(pid, out e) && all.TryGetValue(e.th32ParentProcessID, out parent) + && string.Equals(parent.szExeFile, "Battle.net.exe", StringComparison.OrdinalIgnoreCase)) { + notOurGame.Add(pid); + renewalClients.Add(pid); + continue; + } + ours.Add(pid); + } + if (ours.Count > 0 && gameSeenAt < 0) gameSeenAt = watch.Elapsed.TotalSeconds; + if (gameSeenAt < 0) { + // A new crash reporter for the renewal's closed client: its parent is that client, or (seen too briefly to be + // noted) a process already gone that was not one of the games running before. Any other reporter is left alone. + foreach (uint pid in Pids(all, "BlizzardError.exe")) { + if (oldReporters.Contains(pid)) continue; + oldReporters.Add(pid); + PROCESSENTRY32 reporter; + if (!all.TryGetValue(pid, out reporter)) continue; + uint parentPid = reporter.th32ParentProcessID; + bool renewals = renewalClients.Contains(parentPid) || (!all.ContainsKey(parentPid) && !earlierGames.Contains(parentPid)); + if (!renewals) continue; + try { Process.GetProcessById((int)pid).Kill(); Note("closed crash reporter"); } catch (Exception) { } + } + } + if (!focused) { + var game = Shown(ours); + if (game.Count > 0) { + if (!game.Contains(foreground)) SetForegroundWindow(game[0]); + focused = true; + Note("focused"); + } + } + } + } finally { + UnhookWinEvent(hook); + // Windows the app created but never showed go back where it put them. + foreach (var entry in moved) { + if (!handled.Contains(entry.Key) && IsWindow(entry.Key)) { + SetWindowPos(entry.Key, IntPtr.Zero, entry.Value.Left, entry.Value.Top, 0, 0, SWP_MOVE_ONLY); + } + } + } + } +} +"@ +[BattleNetWindow]::Prepare([bool]$Log) +"ready" +[BattleNetWindow]::Run($Seconds, $GameSeconds, [bool]$FocusGame) diff --git a/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignInTest.java b/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignInTest.java index 5e8ab6a1b..511bb8438 100644 --- a/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignInTest.java +++ b/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignInTest.java @@ -11,8 +11,10 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; +import java.nio.file.Files; import java.nio.file.Path; import java.util.HashSet; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -21,8 +23,63 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.expectThrows; public class BattleNetSignInTest { + @Test + public void aRenewalLockHeldElsewhereIsReportedAsBusy() throws Exception { + if (!Orient.isWindowsSystem()) throw new SkipException("Battle.net paths are Windows paths"); + Path dir = Files.createTempDirectory("wurst-battlenet-lock"); + Path config = dir.resolve("Battle.net.config"); + try (ServerSocket holder = new ServerSocket()) { + holder.bind(new InetSocketAddress(InetAddress.getByAddress(new byte[]{127, 0, 0, 1}), BattleNetSignIn.gatePort(config))); + AtomicBoolean waited = new AtomicBoolean(); + expectThrows(BattleNetSignIn.LockBusyException.class, + () -> BattleNetSignIn.forTest(config, dir).renew(1, () -> waited.set(true))); + assertTrue(waited.get(), "the user is told why the run waits"); + } + } + + @Test + public void aBusyRenewalLockFailsTheRunInsteadOfLaunchingWithoutIt() { + // In "auto" an IOException means "launch on the stored token"; that launch could spend another client's token. + RequestFailedException failure = expectThrows(RequestFailedException.class, () -> RunMap.renewOrRefuse( + onWait -> { throw new BattleNetSignIn.LockBusyException("Another launch holds it."); }, () -> { })); + assertTrue(failure.getMessage().contains("Run the map again"), failure.getMessage()); + // Any other renewal failure still reaches the caller's fallback. + expectThrows(java.io.IOException.class, () -> RunMap.renewOrRefuse( + onWait -> { throw new java.io.IOException("Battle.net is not running."); }, () -> { })); + } + + @Test + public void theWindowWatcherRunsFromACopyNamedByItsContent() throws Exception { + Path dir = Files.createTempDirectory("wurst-window-watcher"); + List command = BattleNetSignIn.windowWatcherCommand(List.of("-Seconds", "30"), dir); + assertEquals(command.subList(0, 6), List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File")); + assertEquals(command.subList(7, command.size()), List.of("-Seconds", "30")); + Path file = Path.of(command.get(6)); + assertEquals(file.getParent(), dir); + String script = Files.readString(file); + assertTrue(script.contains("param([int]$Seconds = 20, [int]$GameSeconds = 60, [switch]$FocusGame, [switch]$Log)")); + assertTrue(script.contains("\"ready\""), "the renewal waits for this line"); + assertTrue(script.chars().allMatch(c -> c < 128), "Windows PowerShell reads a .ps1 without BOM as ANSI"); + assertEquals(BattleNetSignIn.windowWatcherCommand(List.of(), dir).get(6), command.get(6), "the copy is reused"); + } + + @Test + public void theWindowWatcherOutlivesEveryRequestOfASlowRenewal() { + // The renewal asks the app again every 25 s for up to 90 s, and the app shows its window once more as the + // launched client signs in (up to 120 s); each can bring its window back. + assertTrue(BattleNetSignIn.WINDOW_WATCH_SECONDS >= 90 + BattleNetSignIn.SIGN_IN_TIMEOUT_SECONDS, + BattleNetSignIn.WINDOW_WATCH_SECONDS + " s"); + } + + @Test + public void theRenewalLockOutwaitsAnotherRenewalAndItsSignIn() { + assertTrue(BattleNetSignIn.GATE_WAIT_SECONDS > 90 + BattleNetSignIn.SIGN_IN_TIMEOUT_SECONDS, + BattleNetSignIn.GATE_WAIT_SECONDS + " s"); + } + @Test public void aCanceledRenewalKeepsTheLockWhileItWatchesForTheLateClient() throws Exception { ServerSocket gate = new ServerSocket();