207 lines
10 KiB
C#

#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;
private string? boundKey;
private long textChanges;
private (Guid Session, NativeMediaSource Source)? Playback { get; set; }
public NativeMediaSource? ForSession(Guid session)
{
lock (gate) return Playback is { } playback && playback.Session == session ? playback.Source : null;
}
public string Status { get; private set; } = "Start an Audio Review in Writer or Reader.";
public void Select(Guid session, string key)
{
lock (gate)
{
selection = (session, key);
availableReview = Guid.Empty;
Playback = null;
pending = default;
}
}
public void Request(Guid session, string operation)
{
lock (gate)
{
if (Playback is { } playback && playback.Session == session && playback.Source.Operations.Contains(operation) && 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;
var eligible = documents.Where(d => d.Book > 0 && cloud.Allows(d.Authentication, d.Book)).ToArray();
var document = eligible.FirstOrDefault(d => d.Session == selectedSession) ??
eligible.FirstOrDefault(d => d.Active) ?? (eligible.Length == 1 ? eligible[0] : null);
if (document == null)
{
lock (gate) { availableReview = Guid.Empty; Playback = null; }
Status = "Waiting for an authenticated Word document connection.";
continue;
}
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; Playback = null; }
Status = error is InvalidOperationException ? error.Message : "Audio Review telemetry is interrupted. Waiting to reconnect.";
}
}
}
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; Playback = null; }
Status = "Start an Audio Review in Writer or Reader for the linked document.";
return;
}
if (lastReview != review)
{
lastReview = review;
boundKey = null;
textChanges = doc.AudioTextChanges;
}
observation.ReviewID = review;
string? selectedKey;
lock (gate) selectedKey = selection.Session == doc.Session ? selection.Key : null;
var sources = await media.Discover(cancellation);
var expected = string.IsNullOrEmpty(reply.MediaKey) ? boundKey : reply.MediaKey;
var key = AudioSourceSelection.Key(expected, selectedKey,
sources.Where(candidate => candidate.Operations.Length > 0).Select(candidate => candidate.Key));
var source = sources.SingleOrDefault(candidate => candidate.Key == key);
boundKey ??= source?.Key;
(Guid Review, string Operation, DateTime Expiry) local;
lock (gate)
{
availableReview = source?.Operations.Length > 0 ? review : Guid.Empty;
Playback = source == null ? null : (doc.Session, source);
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);
lock (gate) Playback = source != null && observation.MediaKey.Length > 0 ? (doc.Session, source) : null;
Status = observation.Error ?? (source == null
? expected == null && key == null && sources.Count > 1
? "More than one media source is available. Choose Change Audio Source in Companion."
: "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 (boundKey != key || (selection.Session == doc.Session && selection.Key != 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<AudioReviewReply> ObserveAudioReview(TrayDocument doc, AudioReviewObservation observation, CancellationToken cancellation) =>
Send<AudioReviewReply>(HttpMethod.Post,
$"api/native-companion/instances/{doc.Instance}/documents/{doc.Session}/audio-review", observation,
doc.Authentication, cancellation);
}
#endif