Two widget pages share one process (Game Bar + a window). After CrossSound restarted, both reconnected to /events at once; with System.Net.Http on UWP the HTTP cache made the second GET wait for the first to finish, which an event stream never does, and the request had no timeout. - Move to Windows.Web.Http with the cache off and 16 connections per server - Unique query per stream request; headers must arrive within 8 s or retry - Timeouts on commands (10 s) and library calls (30 s) - Connection log in LocalState\widget.log - Skip SoundCloud's "Recently played" shelf (repeats the history) - deploy.ps1: close the widget first, update the layout in place, and re-register a dev-mode package of the same version Co-Authored-By: Claude Opus 5.5 <[email protected]>
367 lines
16 KiB
C#
367 lines
16 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Runtime.InteropServices.WindowsRuntime;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using CrossSoundWidget.Models;
|
|
using Windows.Data.Json;
|
|
using Windows.Storage.Streams;
|
|
using Windows.Web.Http;
|
|
using Windows.Web.Http.Filters;
|
|
|
|
namespace CrossSoundWidget.Services
|
|
{
|
|
public enum ConnectionStatus { Connecting, Connected, NotRunning }
|
|
|
|
public enum LibraryStatus { Ok, SignedOut, NotRunning, Error }
|
|
|
|
public sealed class LibraryResult
|
|
{
|
|
public LibraryStatus Status;
|
|
public IJsonValue Value;
|
|
public string Message;
|
|
|
|
public bool Ok { get { return Status == LibraryStatus.Ok; } }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Everything that talks to CrossSound's local API on 127.0.0.1:8963: the /events and
|
|
/// /appearance/events streams (each its own loop with back-off), commands, artwork and the
|
|
/// SoundCloud library routes. Events are raised on the context it was created on (the UI thread).
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Uses Windows.Web.Http with the HTTP cache off. With the cache on, a second GET for a URL that is
|
|
/// still downloading waits for the first to finish, and an event stream never finishes: two widget
|
|
/// pages in one process reconnecting to /events at once left one waiting forever. Each stream
|
|
/// request also gets a unique query (the server ignores queries) and must see its headers within
|
|
/// <see cref="HeaderTimeout"/>, so a stuck attempt is abandoned and retried.
|
|
/// </remarks>
|
|
public sealed class CrossSoundClient : IDisposable
|
|
{
|
|
public const string BaseUrl = "http://127.0.0.1:8963";
|
|
|
|
private static readonly TimeSpan[] Backoff =
|
|
{
|
|
TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10),
|
|
};
|
|
private static readonly TimeSpan HeaderTimeout = TimeSpan.FromSeconds(8);
|
|
private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(10);
|
|
private static readonly TimeSpan LibraryTimeout = TimeSpan.FromSeconds(30);
|
|
private static int _streamCounter;
|
|
|
|
// Requests time out; the event streams can sit silent for minutes, so they get their own client.
|
|
private readonly HttpClient _http;
|
|
private readonly HttpClient _stream;
|
|
private readonly SynchronizationContext _ui;
|
|
private readonly string _name;
|
|
private CancellationTokenSource _cts;
|
|
private ConnectionStatus _status = ConnectionStatus.Connecting;
|
|
|
|
public event Action<PlayerState> StateReceived;
|
|
public event Action<ConnectionStatus> StatusChanged;
|
|
/// <summary>The app's look, or null when the server has none (Electron and older native: 404).</summary>
|
|
public event Action<JsonObject> AppearanceReceived;
|
|
|
|
public ConnectionStatus Status { get { return _status; } }
|
|
public bool IsRunning { get { return _cts != null; } }
|
|
|
|
/// <param name="name">Tells this client's lines apart in the log (one per widget window).</param>
|
|
public CrossSoundClient(string name)
|
|
{
|
|
_name = name;
|
|
_ui = SynchronizationContext.Current;
|
|
_http = NewClient();
|
|
_stream = NewClient();
|
|
}
|
|
|
|
private static HttpClient NewClient()
|
|
{
|
|
var filter = new HttpBaseProtocolFilter
|
|
{
|
|
AllowUI = false,
|
|
MaxConnectionsPerServer = 16,
|
|
};
|
|
filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.NoCache;
|
|
filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
|
|
return new HttpClient(filter);
|
|
}
|
|
|
|
private static Uri Url(string pathAndQuery) { return new Uri(BaseUrl + pathAndQuery); }
|
|
|
|
public void Start()
|
|
{
|
|
if (_cts != null) return;
|
|
_cts = new CancellationTokenSource();
|
|
var token = _cts.Token;
|
|
Log.Write(_name + " start");
|
|
SetStatus(ConnectionStatus.Connecting);
|
|
var ignored1 = RunStreamAsync("/events", OnStateFrame, null, token);
|
|
var ignored2 = RunStreamAsync("/appearance/events", OnAppearanceFrame, OnAppearanceMissing, token);
|
|
}
|
|
|
|
public void Stop()
|
|
{
|
|
if (_cts == null) return;
|
|
Log.Write(_name + " stop");
|
|
_cts.Cancel();
|
|
_cts.Dispose();
|
|
_cts = null;
|
|
}
|
|
|
|
/// <summary>Stop and start again now, skipping whatever back-off is pending.</summary>
|
|
public void Reconnect()
|
|
{
|
|
Stop();
|
|
Start();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- event streams
|
|
|
|
private async Task RunStreamAsync(string path, Action<string> onFrame, Func<int, bool> onRefused, CancellationToken token)
|
|
{
|
|
var failures = 0;
|
|
while (!token.IsCancellationRequested)
|
|
{
|
|
var gotFrame = false;
|
|
var frames = 0;
|
|
var outcome = "ended";
|
|
HttpResponseMessage response = null;
|
|
IInputStream input = null;
|
|
try
|
|
{
|
|
var request = new HttpRequestMessage(HttpMethod.Get, Url(path + "?c=" + Interlocked.Increment(ref _streamCounter)));
|
|
request.Headers.Accept.TryParseAdd("text/event-stream");
|
|
using (var headers = CancellationTokenSource.CreateLinkedTokenSource(token))
|
|
{
|
|
headers.CancelAfter(HeaderTimeout);
|
|
response = await _stream.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead).AsTask(headers.Token).ConfigureAwait(false);
|
|
}
|
|
|
|
var code = (int)response.StatusCode;
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
outcome = "HTTP " + code;
|
|
// The server is up but won't stream this (appearance on Electron / older builds).
|
|
if (onRefused != null && onRefused(code)) failures = Backoff.Length - 1;
|
|
}
|
|
else
|
|
{
|
|
Log.Write(_name + " " + path + " connected");
|
|
input = await response.Content.ReadAsInputStreamAsync().AsTask(token).ConfigureAwait(false);
|
|
var captured = response;
|
|
var capturedInput = input;
|
|
using (token.Register(() => { capturedInput.Dispose(); captured.Dispose(); }))
|
|
using (var reader = new StreamReader(input.AsStreamForRead(0), Encoding.UTF8))
|
|
{
|
|
var data = new StringBuilder();
|
|
string line;
|
|
while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
|
|
{
|
|
if (token.IsCancellationRequested) break;
|
|
if (line.Length == 0)
|
|
{
|
|
if (data.Length > 0)
|
|
{
|
|
gotFrame = true;
|
|
frames++;
|
|
failures = 0;
|
|
var frame = data.ToString();
|
|
data.Clear();
|
|
Post(() => onFrame(frame));
|
|
}
|
|
continue;
|
|
}
|
|
if (line.StartsWith("data:", StringComparison.Ordinal))
|
|
{
|
|
var payload = line.Substring(5);
|
|
if (payload.StartsWith(" ", StringComparison.Ordinal)) payload = payload.Substring(1);
|
|
if (data.Length > 0) data.Append('\n');
|
|
data.Append(payload);
|
|
}
|
|
// ":" comments, "event:", "id:" and "retry:" lines are ignored.
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
outcome = token.IsCancellationRequested ? "cancelled" : "no headers within " + HeaderTimeout.TotalSeconds + " s";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
outcome = "error 0x" + ex.HResult.ToString("X8") + " " + ex.Message.Split('\r', '\n')[0];
|
|
}
|
|
finally
|
|
{
|
|
if (input != null) input.Dispose();
|
|
if (response != null) response.Dispose();
|
|
}
|
|
|
|
if (token.IsCancellationRequested) break;
|
|
|
|
var delay = Backoff[Math.Min(failures, Backoff.Length - 1)];
|
|
failures++;
|
|
if (path == "/events" || !outcome.StartsWith("HTTP 404", StringComparison.Ordinal))
|
|
Log.Write(_name + " " + path + " " + outcome + " after " + frames + " frame(s); retry in " + delay.TotalSeconds + " s");
|
|
|
|
if (path == "/events")
|
|
{
|
|
// A stream that ended after frames is probably the app quitting or restarting:
|
|
// say "connecting" and try again soon. One that never connected means it isn't running.
|
|
var next = gotFrame ? ConnectionStatus.Connecting : ConnectionStatus.NotRunning;
|
|
Post(() => { if (!token.IsCancellationRequested) SetStatus(next); });
|
|
}
|
|
|
|
try { await Task.Delay(delay, token).ConfigureAwait(false); }
|
|
catch (OperationCanceledException) { break; }
|
|
}
|
|
}
|
|
|
|
private void OnStateFrame(string frame)
|
|
{
|
|
var obj = Json.Parse(frame);
|
|
if (obj == null) return;
|
|
SetStatus(ConnectionStatus.Connected);
|
|
var handler = StateReceived;
|
|
if (handler != null) handler(PlayerState.Parse(obj));
|
|
}
|
|
|
|
private void OnAppearanceFrame(string frame)
|
|
{
|
|
var obj = Json.Parse(frame);
|
|
if (obj == null) return;
|
|
var handler = AppearanceReceived;
|
|
if (handler != null) handler(obj);
|
|
}
|
|
|
|
private bool OnAppearanceMissing(int code)
|
|
{
|
|
Post(() =>
|
|
{
|
|
var handler = AppearanceReceived;
|
|
if (handler != null) handler(null);
|
|
});
|
|
return true;
|
|
}
|
|
|
|
private void SetStatus(ConnectionStatus status)
|
|
{
|
|
if (_status == status) return;
|
|
_status = status;
|
|
Log.Write(_name + " status " + status);
|
|
var handler = StatusChanged;
|
|
if (handler != null) handler(status);
|
|
}
|
|
|
|
private void Post(Action action)
|
|
{
|
|
if (_ui != null) _ui.Post(_ => action(), null);
|
|
else action();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- requests
|
|
|
|
private async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, TimeSpan timeout)
|
|
{
|
|
using (var cts = new CancellationTokenSource(timeout))
|
|
{
|
|
return await _http.SendRequestAsync(request, HttpCompletionOption.ResponseContentRead).AsTask(cts.Token).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
/// <summary>POST /command {action, ...data}. True when the server answered 2xx.</summary>
|
|
public async Task<bool> CommandAsync(string action, JsonObject data = null)
|
|
{
|
|
var body = new JsonObject();
|
|
body["action"] = JsonValue.CreateStringValue(action);
|
|
if (data != null)
|
|
{
|
|
foreach (var pair in data) body[pair.Key] = pair.Value;
|
|
}
|
|
try
|
|
{
|
|
var request = new HttpRequestMessage(HttpMethod.Post, Url("/command"))
|
|
{
|
|
Content = new HttpStringContent(body.Stringify(), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"),
|
|
};
|
|
using (var response = await SendAsync(request, RequestTimeout).ConfigureAwait(false))
|
|
{
|
|
if (!response.IsSuccessStatusCode) Log.Write(_name + " command " + action + ": HTTP " + (int)response.StatusCode);
|
|
return response.IsSuccessStatusCode;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Write(_name + " command " + action + " failed: 0x" + ex.HResult.ToString("X8"));
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The current cover's bytes. /artwork has a fixed URL with max-age=60, so the query carries a
|
|
/// hash of the snapshot's artwork URL (the cache is off here too, belt and braces).
|
|
/// </summary>
|
|
public async Task<byte[]> GetArtworkAsync(string artworkUrl)
|
|
{
|
|
var v = ((uint)StableHash(artworkUrl ?? "")).ToString("x8", System.Globalization.CultureInfo.InvariantCulture);
|
|
try
|
|
{
|
|
using (var response = await SendAsync(new HttpRequestMessage(HttpMethod.Get, Url("/artwork?v=" + v)), RequestTimeout).ConfigureAwait(false))
|
|
{
|
|
if (!response.IsSuccessStatusCode) return null;
|
|
var buffer = await response.Content.ReadAsBufferAsync().AsTask().ConfigureAwait(false);
|
|
return buffer != null && buffer.Length > 0 ? buffer.ToArray() : null;
|
|
}
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public async Task<LibraryResult> GetJsonAsync(string pathAndQuery)
|
|
{
|
|
try
|
|
{
|
|
using (var response = await SendAsync(new HttpRequestMessage(HttpMethod.Get, Url(pathAndQuery)), LibraryTimeout).ConfigureAwait(false))
|
|
{
|
|
var text = await response.Content.ReadAsStringAsync().AsTask().ConfigureAwait(false);
|
|
var value = Json.ParseValue(text);
|
|
if (response.IsSuccessStatusCode)
|
|
return new LibraryResult { Status = LibraryStatus.Ok, Value = value };
|
|
|
|
var error = Json.Str(Json.AsObject(value), "error") ?? ("HTTP " + (int)response.StatusCode);
|
|
Log.Write(_name + " GET " + pathAndQuery + ": " + error);
|
|
if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
|
|
return new LibraryResult { Status = LibraryStatus.SignedOut, Message = error };
|
|
return new LibraryResult { Status = LibraryStatus.Error, Message = error };
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Write(_name + " GET " + pathAndQuery + " failed: 0x" + ex.HResult.ToString("X8"));
|
|
return new LibraryResult { Status = LibraryStatus.NotRunning, Message = "Can't reach CrossSound" };
|
|
}
|
|
}
|
|
|
|
/// <summary>FNV-1a; string.GetHashCode is randomized per process.</summary>
|
|
private static int StableHash(string s)
|
|
{
|
|
unchecked
|
|
{
|
|
var h = (int)2166136261;
|
|
foreach (var ch in s) h = (h ^ ch) * 16777619;
|
|
return h;
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Stop();
|
|
_http.Dispose();
|
|
_stream.Dispose();
|
|
}
|
|
}
|
|
}
|