Reported 2026-09-27: click avatar -> Change Account -> cancel in the Google chooser -> back to a signed-out app, then "cannot sign-in because the callback url was not released". Two independent defects: 1. ChangeAccountAsync ran `await SignOutYouTubeAsync(); await SignInAsync();`. SignOutYouTubeAsync -> TokenStore.Clear() -> deletes ytLlive.auth, so the working account's token was destroyed before the browser even opened. It is now just `await SignInAsync()`: success overwrites the token via the sessionChanged hook, cancel/failure keeps the current session. The explicit sign-out was never needed. 2. Abandoning the browser gives the app no signal, so the OAuth attempt held localhost:8765 for its full 5-minute timeout and a retry could not bind. A new AuthenticateAsync now cancels and awaits the abandoned attempt first. That takeover is serialised by a SemaphoreSlim: the first version cleared the in-flight marker before awaiting, so a caller arriving in that window saw a free port and raced to bind it -- reproducing the very failure it was written to prevent. My own test caught that; reasoning had "proved" it fine. Also adds an `openBrowser` ctor seam so tests never shell out to a real browser, and corrects the ai.md line that documented "Logout / Change Account -> SignOutYouTubeAsync" as intended behaviour. Test: YouTubeAuthServiceTests.RetryingAfterAnAbandonedAttempt_ReleasesTheCallbackPort Full suite 370/370, 0 warnings. Coverage gap noted in HANDOFF.md: the ordering fix has no automated test because _youtubeAuth is hardcoded in MainViewModel and ChangeAccountAsync is private. The reported cross-instance effect is NOT this cause and stays open -- no code path can sign out a second instance (per-instance TokenStore, local delete, no server-side revoke).
146 lines
5.4 KiB
C#
146 lines
5.4 KiB
C#
using ytLive.Helpers;
|
|
using ytLive.Models;
|
|
using ytLive.Services;
|
|
|
|
namespace ytLive.ViewModels;
|
|
|
|
public partial class MainViewModel
|
|
{
|
|
private bool _isConnected;
|
|
private string _accountAvatarUrl = string.Empty;
|
|
private string _accountDisplayName = string.Empty;
|
|
|
|
public bool IsConnected
|
|
{
|
|
get => _isConnected;
|
|
set
|
|
{
|
|
if (SetProperty(ref _isConnected, value))
|
|
{
|
|
// ON-AIR requires a sign-in; dropping the session turns the pill
|
|
// off so the state can never offer a stream without an account.
|
|
if (!value) OnAirPillOn = false;
|
|
RaiseTopBarModes();
|
|
OnPropertyChanged(nameof(AccountStatusLightToolTip));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>The connected YouTube account's avatar + name — shown in the top
|
|
/// bar so the creator always sees WHICH account is about to go live.</summary>
|
|
public string AccountAvatarUrl
|
|
{
|
|
get => _accountAvatarUrl;
|
|
private set => SetProperty(ref _accountAvatarUrl, value);
|
|
}
|
|
|
|
public string AccountDisplayName
|
|
{
|
|
get => _accountDisplayName;
|
|
private set => SetProperty(ref _accountDisplayName, value);
|
|
}
|
|
|
|
/// <summary>Tooltip for the account status light explaining the color.</summary>
|
|
public string AccountStatusLightToolTip =>
|
|
IsLive ? "Live on YouTube — the top bar is red to show the stream is on the air."
|
|
: IsConnected ? "You're signed in to YouTube. The light is green; ON-AIR is available."
|
|
: "Signed out — the light is red. You can still record locally; arming ON-AIR arms intent, and Start turns that intent into a sign-in.";
|
|
|
|
// Restores the DPAPI-saved OAuth session so sign-in survives restarts.
|
|
// Best-effort: refresh a near-expiry access token; a session that can no
|
|
// longer refresh is discarded and the user signs in again.
|
|
private async Task LoadSavedSessionAsync()
|
|
{
|
|
try
|
|
{
|
|
var saved = TokenStore.Load();
|
|
if (saved == null) return;
|
|
|
|
_youtubeAuth.SetSession(saved);
|
|
if (saved.TokenExpiry <= DateTime.UtcNow.AddMinutes(5))
|
|
{
|
|
var refreshed = await Task.Run(() => _youtubeAuth.RefreshToken());
|
|
if (!refreshed)
|
|
{
|
|
TokenStore.Clear();
|
|
AppLog.Write("Saved session could not be refreshed; signed out");
|
|
_notifications.Info("Signed out of YouTube",
|
|
"The saved session expired — sign in again when you next go live.");
|
|
return;
|
|
}
|
|
}
|
|
|
|
IsConnected = true;
|
|
SyncConnectedAccount();
|
|
Ypp.OnAccountChanged();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
AppLog.Write($"LoadSavedSessionAsync failed: {ex}");
|
|
}
|
|
}
|
|
|
|
private void SyncConnectedAccount()
|
|
{
|
|
var channel = _youtubeAuth.CurrentChannel;
|
|
AccountAvatarUrl = channel?.ProfileImageUrl ?? string.Empty;
|
|
AccountDisplayName = channel?.DisplayName ?? string.Empty;
|
|
}
|
|
|
|
// Runs the OAuth flow (browser + loopback callback) on a background thread.
|
|
// The resulting channel is returned to the caller and persisted via the
|
|
// auth service's sessionChanged hook.
|
|
private async Task<YouTubeChannel?> SignInAsync()
|
|
{
|
|
try
|
|
{
|
|
var channel = await Task.Run(() => _youtubeAuth.AuthenticateAsync());
|
|
if (channel == null)
|
|
{
|
|
_notifications.Warning("Sign-in was unsuccessful", "Please try again.");
|
|
return null;
|
|
}
|
|
|
|
IsConnected = true;
|
|
SyncConnectedAccount();
|
|
Ypp.OnAccountChanged();
|
|
return channel;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_notifications.Error("Sign-in failed", ex.Message);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>Signs out of YouTube (the delete-the-YouTube-slot action in the dialog).</summary>
|
|
private async Task SignOutYouTubeAsync()
|
|
{
|
|
_youtubeAuth.ClearSession();
|
|
TokenStore.Clear();
|
|
IsConnected = false;
|
|
SyncConnectedAccount();
|
|
NotifySocialsChanged();
|
|
Ypp.OnAccountChanged();
|
|
AppLog.Write("Socials: signed out of YouTube");
|
|
await Task.CompletedTask;
|
|
}
|
|
|
|
/// <summary>Change account: sign in to a different YouTube account WITHOUT
|
|
/// destroying the current session first.
|
|
/// <para><b>The bug this fixes (2026-09-27).</b> This used to be
|
|
/// <c>await SignOutYouTubeAsync(); await SignInAsync();</c> — it signed out
|
|
/// <i>before</i> opening the browser, and <c>SignOutYouTubeAsync</c> calls
|
|
/// <c>TokenStore.Clear()</c>, which DELETES the saved token file. The creator
|
|
/// clicked "Change Account", cancelled in the Google account chooser, and came
|
|
/// back to an app that had already thrown away a working, signed-in account.
|
|
/// </para>
|
|
/// <para>No sign-out is needed at all: on success <see cref="SignInAsync"/>
|
|
/// replaces the session and the <c>sessionChanged</c> hook overwrites the token
|
|
/// file with the new account. On cancel or failure it returns null and leaves
|
|
/// the current session untouched — which is the behaviour that was wanted.</para></summary>
|
|
private async Task ChangeAccountAsync()
|
|
{
|
|
await SignInAsync();
|
|
}
|
|
} |