#if WINDOWS using System.Text.Json; using PlotDirector.Companion.Protocol; namespace PlotDirector.Companion.Agent; internal sealed class WindowsAudioReview(CloudGateway cloud, TrayCoordinator tray, WindowsMediaControl media, string directory) { private readonly string receipts = Path.Combine(directory, "audio-review-receipts"); private readonly object gate = new(); private (Guid Session, string Key) selection; private (Guid Review, string Operation, DateTime Expiry) pending; private Guid availableReview; private long sequence = DateTime.UtcNow.Ticks; private Guid lastReview, blockedReview; private long textChanges; private bool sourceSeen; public string Status { get; private set; } = "Select a Windows media source to connect Audio Review."; public void Select(Guid session, string key) { lock (gate) { selection = (session, key); availableReview = Guid.Empty; pending = default; } } public void Request(Guid session, string operation) { lock (gate) { if (selection.Session == session && availableReview != Guid.Empty) pending = (availableReview, operation, DateTime.UtcNow.AddSeconds(10)); } } public async Task Run(CancellationToken cancellation) { using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2)); while (await timer.WaitForNextTickAsync(cancellation)) { var documents = tray.PresentationDocuments; Guid selectedSession; lock (gate) selectedSession = selection.Session; foreach (var document in documents.Where(d => d.Session == selectedSession && d.Book > 0 && cloud.Allows(d.Authentication, d.Book))) { try { await Observe(document, cancellation); } catch (Exception error) when (error is IOException or HttpRequestException or InvalidOperationException or OperationCanceledException or System.Runtime.InteropServices.COMException or JsonException or PlatformNotSupportedException) { lock (gate) availableReview = Guid.Empty; Status = "Audio Review is unavailable. Check the Companion connection and selected media source."; } } } } private async Task Observe(TrayDocument doc, CancellationToken cancellation) { var observation = new AudioReviewObservation { BookID = doc.Book, Sequence = ++sequence }; var reply = await cloud.ObserveAudioReview(doc, observation, cancellation); if (reply.Version != 1 || reply.ReviewID is not Guid review || review == Guid.Empty) { lock (gate) availableReview = Guid.Empty; Status = "Start an Audio Review in Writer or Reader for the linked document."; return; } if (lastReview != review) { lastReview = review; sourceSeen = false; textChanges = doc.AudioTextChanges; } observation.ReviewID = review; string? key; lock (gate) key = selection.Session == doc.Session ? selection.Key : null; if (!string.IsNullOrEmpty(reply.MediaKey) && reply.MediaKey != key) key = null; NativeMediaSource? source = null; if (key != null) { try { source = (await media.Discover(cancellation)).SingleOrDefault(s => s.Key == key); } catch (Exception error) when (error is OperationCanceledException or System.Runtime.InteropServices.COMException) { cancellation.ThrowIfCancellationRequested(); } } if (source == null && sourceSeen) blockedReview = review; if (blockedReview == review) source = null; sourceSeen |= source != null; (Guid Review, string Operation, DateTime Expiry) local; lock (gate) { availableReview = source == null ? Guid.Empty : review; local = pending; pending = default; } if (doc.AudioTextChanges != textChanges) { textChanges = doc.AudioTextChanges; observation.TextModified = true; if (reply.PauseOnEdit && source is { State: "playing" } && IsCurrent(doc, source.Key)) { try { await media.Execute(source.Key, "pause", DateTime.UtcNow.AddSeconds(2), cancellation); } catch (Exception error) when (error is OperationCanceledException or System.Runtime.InteropServices.COMException) { cancellation.ThrowIfCancellationRequested(); } source = (await media.Discover(cancellation)).SingleOrDefault(s => s.Key == key); } } if (reply.CommandID is Guid command && command != Guid.Empty) { observation.AcknowledgedCommandID = command; var path = Path.Combine(receipts, review.ToString("N"), command.ToString("N")); Directory.CreateDirectory(Path.GetDirectoryName(path)!); if (File.Exists(path)) ApplyReceipt(observation, File.ReadAllText(path)); else { // Persist intent before invoking a non-idempotent OS seek. A crash leaves an // unknown outcome, which is acknowledged without replaying the command. using (var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1, FileOptions.WriteThrough)) { file.WriteByte((byte)'?'); file.Flush(true); } var succeeded = false; var operation = reply.Command; if (source != null && operation != null && (!observation.TextModified || !reply.PauseOnEdit || operation != "play") && reply.MediaKey == source.Key && reply.ExpiresUtc is DateTime expiry && expiry > DateTime.UtcNow && (operation == "back15" ? reply.RelativeSeconds == -15 : operation == "forward15" ? reply.RelativeSeconds == 15 : reply.RelativeSeconds == null) && IsCurrent(doc, source.Key)) { try { succeeded = await media.Execute(source.Key, operation, expiry, cancellation); } catch (Exception error) when (error is OperationCanceledException or System.Runtime.InteropServices.COMException) { cancellation.ThrowIfCancellationRequested(); } } var result = succeeded ? operation is "back15" or "forward15" ? "seek" : "ok" : "failed"; var temporary = path + ".tmp"; File.WriteAllText(temporary, result); File.Move(temporary, path, true); ApplyReceipt(observation, result); if (source != null) source = (await media.Discover(cancellation)).SingleOrDefault(s => s.Key == key); } } else if (source != null && local.Review == review && IsCurrent(doc, source.Key) && (!observation.TextModified || !reply.PauseOnEdit || local.Operation != "play")) { var succeeded = await media.Execute(source.Key, local.Operation, local.Expiry, cancellation); observation.Seeked = succeeded && local.Operation is "back15" or "forward15"; if (!succeeded) observation.Error = "The Windows media operation was unavailable or refused."; source = (await media.Discover(cancellation)).SingleOrDefault(s => s.Key == key); } if (source != null && IsCurrent(doc, source.Key)) { observation.State = source.State; observation.MediaKey = source.Key; observation.PositionSeconds = source.Position; observation.DurationSeconds = source.Duration; observation.PlaybackRate = source.Rate; observation.Operations = source.Operations; } observation.Sequence = ++sequence; await cloud.ObserveAudioReview(doc, observation, cancellation); Status = observation.Error ?? (source == null ? "The selected media source is unavailable. End and restart Audio Review if the media source changed." : $"Windows media source: {source.Application} ยท {observation.State}"); } private bool IsCurrent(TrayDocument doc, string key) { lock (gate) if (selection != (doc.Session, key)) return false; return cloud.Allows(doc.Authentication, doc.Book) && tray.PresentationDocuments.Any(d => d.Session == doc.Session && d.Instance == doc.Instance && d.Book == doc.Book && d.Authentication == doc.Authentication); } private static void ApplyReceipt(AudioReviewObservation observation, string receipt) { observation.Seeked = receipt == "seek"; observation.Error = receipt switch { "seek" or "ok" => null, "?" => "The previous Windows command outcome is unknown.", _ => "The Windows media command was unavailable, expired or refused." }; } } public sealed partial class CloudGateway { internal Task ObserveAudioReview(TrayDocument doc, AudioReviewObservation observation, CancellationToken cancellation) => Send(HttpMethod.Post, $"api/native-companion/instances/{doc.Instance}/documents/{doc.Session}/audio-review", observation, doc.Authentication, cancellation); } #endif