cb750660c3
Creator: 'when I attempt to refresh my YPP page, I get an error about not being able to reach YouTube. Seriously?' Real log: channels.list failed (403) x3. Root cause #1 (the 403): channels.list?mine=true&part=statistics,auditDetails, contentDetails returns 403 insufficientPermissions when the token lacks the youtubepartner-channel-audit scope — which the auditDetails part ALONE requires, per the docs ('A request that retrieves the auditDetails part ... must provide an authorization token that contains the youtubepartner-channel-audit scope'). That scope is MCN partner tooling with a 2-week token-revocation rule; the app must not hold it. TASK-39's 'current scopes suffice, no re-consent' slice-1 claim was wrong for this part; mock-fake tests never touched the real API, so it shipped green and 403'd every refresh since 2026-09-22. https://developers.google.com/youtube/v3/docs/channels/list Fix: part=statistics,contentDetails only; standing flags removed from ChannelStatsService -> YppStatSnapshot surface -> YppTrackerViewModel -> drawer, replaced by an honest deep-link row ('Channel standing isn't exposed to YouTube apps — check the Earn page'). YppSnapshot standing columns stay (schema-stable, always false). channels.list failures now log the response BODY — the bare code could not name insufficientPermissions, which is what made this undiagnosable. Root cause #2 (found by the new Good Dog, masked by the 403): statistics come back as JSON STRINGS ('350'); raw GetInt64() throws. Tolerant ReadInt64 (ValueKind-first; JsonElement.TryGetInt64 THROWS on strings — type-in, not try-type). Good Dog: ChannelStatsServiceTests.CaptureCurrent_RequestsNoAuditDetails_AndStillParsesTheSnapshot (URL asserts no auditDetails + snapshot parses); YppPullOutTests fixture updated. Recipes for both 403/scope and statistics-strings entered in MyMistakes.md. Also shipped in the same commit (shared PreviewPane.xaml + ai.md): the audio-sync status dot removal from the #77 feedback round (creator: 'what is the point of the status light? Lose it') — IntToSyncBrushConverter deleted with it. verify.sh gate: 0 warnings, 316/316 pass, scope-check clean.
282 lines
11 KiB
C#
282 lines
11 KiB
C#
using System.Diagnostics;
|
|
using System.Windows.Input;
|
|
using ytLive.Helpers;
|
|
using ytLive.Models;
|
|
|
|
namespace ytLive.Services;
|
|
|
|
/// <summary>
|
|
/// Backing VM for the YPP pull-out (the "YPP" tab below Stream Settings on the
|
|
/// Live screen's right edge). Shows the connected channel's current position
|
|
/// toward the YPP tier thresholds (subscribers + 90-day uploads via the Data
|
|
/// API), a compliance checklist (2FA/AdSense self-reported — channel standing is
|
|
/// NOT exposed to ordinary apps, so the drawer deep-links to the Earn page for it)
|
|
/// and the "what counts" education the creator would otherwise have to leave the
|
|
/// app to find. Snapshots are appended to SQLite on every refresh so a later
|
|
/// analytics slice can compute velocity/ETA from history.
|
|
/// Drawer open/close lives here (mirrors LiveBroadcastFormViewModel).
|
|
/// </summary>
|
|
public sealed class YppTrackerViewModel : ViewModelBase
|
|
{
|
|
private const double BarMaxWidth = 220;
|
|
|
|
private readonly Func<LayoutStore> _store;
|
|
private readonly Func<ChannelStatsService> _stats;
|
|
private readonly Func<bool> _isConnected;
|
|
private readonly Func<string?> _displayName;
|
|
|
|
private bool _isDrawerOpen;
|
|
private bool _isLoading;
|
|
private bool _isRefreshing;
|
|
private string? _loadError;
|
|
private string _displayNameText = string.Empty;
|
|
private long _subscriberCount;
|
|
private long _videoCount;
|
|
private long _totalViews;
|
|
private int _uploadsLast90Days;
|
|
private bool _hasSnapshot;
|
|
private bool _twoFactorEnabled;
|
|
private bool _adsenseLinked;
|
|
private DateTime? _lastRefreshedAtUtc;
|
|
|
|
public YppTrackerViewModel(
|
|
Func<LayoutStore> store,
|
|
Func<ChannelStatsService> stats,
|
|
Func<bool> isConnected,
|
|
Func<string?> displayName)
|
|
{
|
|
_store = store;
|
|
_stats = stats;
|
|
_isConnected = isConnected;
|
|
_displayName = displayName;
|
|
|
|
RefreshCommand = new RelayCommand(_ => _ = RefreshAsync());
|
|
ToggleDrawerCommand = new RelayCommand(_ => IsDrawerOpen = !IsDrawerOpen);
|
|
CloseDrawerCommand = new RelayCommand(_ => IsDrawerOpen = false);
|
|
OpenEarnCommand = new RelayCommand(_ => OpenUrl(EarnUrl));
|
|
OpenTwoStepCommand = new RelayCommand(_ => OpenUrl(TwoStepVerificationUrl));
|
|
OpenAdsenseCommand = new RelayCommand(_ => OpenUrl(AdsenseGuideUrl));
|
|
|
|
(_twoFactorEnabled, _adsenseLinked) = _store().LoadYppChecklist();
|
|
_lastRefreshedAtUtc = _store().LoadYppLastRefreshedAtUtc();
|
|
}
|
|
|
|
// Deep links — the parts of the checklist YouTube does NOT expose to any API
|
|
// resolve in the browser; everything API-derived stays in-app.
|
|
private const string EarnUrl = "https://www.youtube.com/earn";
|
|
private const string TwoStepVerificationUrl = "https://myaccount.google.com/signinoptions/two-step-verification";
|
|
private const string AdsenseGuideUrl = "https://support.google.com/youtube/answer/72851";
|
|
|
|
public RelayCommand RefreshCommand { get; }
|
|
public RelayCommand ToggleDrawerCommand { get; }
|
|
public RelayCommand CloseDrawerCommand { get; }
|
|
public RelayCommand OpenEarnCommand { get; }
|
|
public RelayCommand OpenTwoStepCommand { get; }
|
|
public RelayCommand OpenAdsenseCommand { get; }
|
|
|
|
public bool IsDrawerOpen
|
|
{
|
|
get => _isDrawerOpen;
|
|
set
|
|
{
|
|
if (SetProperty(ref _isDrawerOpen, value) && value)
|
|
_ = EnsureLoadedAsync();
|
|
}
|
|
}
|
|
|
|
public bool IsLoading
|
|
{
|
|
get => _isLoading;
|
|
private set => SetProperty(ref _isLoading, value);
|
|
}
|
|
|
|
public bool IsSignedOut => !_isConnected();
|
|
|
|
public string? LoadError
|
|
{
|
|
get => _loadError;
|
|
private set => SetProperty(ref _loadError, value);
|
|
}
|
|
|
|
public string DisplayName => _displayNameText;
|
|
|
|
// ─── Live numbers (from the Data API snapshot) ───
|
|
|
|
public long SubscriberCount => _subscriberCount;
|
|
public long VideoCount => _videoCount;
|
|
public long TotalViews => _totalViews;
|
|
public int UploadsLast90Days => _uploadsLast90Days;
|
|
|
|
/// <summary>True once a snapshot has successfully captured at least once this
|
|
/// session (drives the standing detail text's "sign in to load" state).</summary>
|
|
public bool HasSnapshot => _hasSnapshot;
|
|
|
|
// ─── Manual checklist (2FA / AdSense — no API exposes them) ───
|
|
|
|
public bool TwoFactorEnabled
|
|
{
|
|
get => _twoFactorEnabled;
|
|
set
|
|
{
|
|
if (SetProperty(ref _twoFactorEnabled, value))
|
|
PersistChecklist();
|
|
}
|
|
}
|
|
|
|
public bool AdSenseLinked
|
|
{
|
|
get => _adsenseLinked;
|
|
set
|
|
{
|
|
if (SetProperty(ref _adsenseLinked, value))
|
|
PersistChecklist();
|
|
}
|
|
}
|
|
|
|
// ─── Progress rows (subscribers is fixed; uploads is a 3/90d bar) ───
|
|
|
|
public double Tier1SubsProgress => Progress(SubscriberCount, YppThresholds.Tier1.Subscribers);
|
|
public double Tier2SubsProgress => Progress(SubscriberCount, YppThresholds.Tier2Now.Subscribers);
|
|
public double UploadsProgress => Progress(UploadsLast90Days, YppThresholds.UploadsRequiredPer90Days);
|
|
|
|
public double Tier1SubsBarWidth => Progress(SubscriberCount, YppThresholds.Tier1.Subscribers) * BarMaxWidth;
|
|
public double Tier2SubsBarWidth => Progress(SubscriberCount, YppThresholds.Tier2Now.Subscribers) * BarMaxWidth;
|
|
public double UploadsBarWidth => Progress(UploadsLast90Days, YppThresholds.UploadsRequiredPer90Days) * BarMaxWidth;
|
|
|
|
public string Tier1SubsText => $"{SubscriberCount:N0} / {YppThresholds.Tier1.Subscribers:N0}";
|
|
public string Tier2SubsText => $"{SubscriberCount:N0} / {YppThresholds.Tier2Now.Subscribers:N0}";
|
|
public string UploadsText => $"{UploadsLast90Days} / {YppThresholds.UploadsRequiredPer90Days} in the last 90 days";
|
|
|
|
public string StandingDetailText
|
|
{
|
|
get
|
|
{
|
|
if (!HasSnapshot) return "Sign in to load your channel's progress from YouTube.";
|
|
return "Channel standing isn't exposed to YouTube apps — check the Earn page for your live status.";
|
|
}
|
|
}
|
|
|
|
public string LastUpdatedText
|
|
{
|
|
get
|
|
{
|
|
if (_lastRefreshedAtUtc == null) return "Not refreshed yet";
|
|
var local = _lastRefreshedAtUtc.Value.ToLocalTime();
|
|
return local.Date == DateTime.Today
|
|
? $"Updated today at {local:HH:mm}"
|
|
: $"Updated {local:g}";
|
|
}
|
|
}
|
|
|
|
public string WhatCountsText { get; } =
|
|
"Long-form watch hours: valid public VODs and livestreams watched in the trailing 12 " +
|
|
"months — Shorts-feed views don't count, and private, unlisted, deleted or ad-campaign " +
|
|
"time is excluded. Shorts views: valid public Shorts viewed in the Shorts feed over 90 " +
|
|
"days. Uploads: valid public long-form videos posted in the last 90 days. Zero active " +
|
|
"Community Guidelines strikes, 2-Step Verification switched on, and a linked AdSense " +
|
|
"account complete the checklist. Figures here are API-derived and close to — but not " +
|
|
"identical to — YouTube Studio's Earn tab.";
|
|
|
|
/// <summary>Account sign-in/out changed (fires from MainViewModel): reset the
|
|
/// signed-out state and refresh when a session now exists.</summary>
|
|
public void OnAccountChanged()
|
|
{
|
|
OnPropertyChanged(nameof(IsSignedOut));
|
|
OnPropertyChanged(nameof(DisplayName));
|
|
if (_hasSnapshot && !_isConnected())
|
|
{
|
|
_hasSnapshot = false;
|
|
OnPropertyChanged(nameof(HasSnapshot));
|
|
}
|
|
if (_isConnected())
|
|
_ = EnsureLoadedAsync();
|
|
}
|
|
|
|
/// <summary>Loads once per session/day (quota-honest: the analytics slice that
|
|
/// gives watch-hours/shorts has a thin targeted-query budget, so this gate is
|
|
/// baked in now). A manual "Refresh" always goes to the wire.</summary>
|
|
public async Task EnsureLoadedAsync()
|
|
{
|
|
if (!_isConnected() || _hasSnapshot) return;
|
|
var last = _store().LoadYppLastRefreshedAtUtc();
|
|
if (last != null && DateTime.UtcNow - last.Value < TimeSpan.FromHours(24)) return;
|
|
await RefreshAsync();
|
|
}
|
|
|
|
public async Task RefreshAsync()
|
|
{
|
|
if (_isRefreshing) return;
|
|
_isRefreshing = true;
|
|
IsLoading = true;
|
|
LoadError = null;
|
|
try
|
|
{
|
|
if (!_isConnected())
|
|
{
|
|
_lastRefreshedAtUtc = null;
|
|
OnPropertyChanged(nameof(LastUpdatedText));
|
|
return;
|
|
}
|
|
|
|
var snapshot = await _stats().CaptureCurrentAsync();
|
|
if (snapshot == null)
|
|
{
|
|
LoadError = "Couldn't reach YouTube — try again.";
|
|
return;
|
|
}
|
|
|
|
ApplySnapshot(snapshot);
|
|
_store().SaveYppSnapshot(snapshot);
|
|
_lastRefreshedAtUtc = snapshot.CapturedAtUtc;
|
|
_store().SaveYppLastRefreshedAtUtc(snapshot.CapturedAtUtc);
|
|
OnPropertyChanged(nameof(LastUpdatedText));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
AppLog.Write($"YPP refresh failed: {ex}");
|
|
LoadError = "Refresh failed — try again.";
|
|
}
|
|
finally
|
|
{
|
|
_isRefreshing = false;
|
|
IsLoading = false;
|
|
}
|
|
}
|
|
|
|
private void ApplySnapshot(YppStatSnapshot snapshot)
|
|
{
|
|
_displayNameText = _displayName() ?? string.Empty;
|
|
_subscriberCount = snapshot.SubscriberCount;
|
|
_videoCount = snapshot.VideoCount;
|
|
_totalViews = snapshot.TotalViews;
|
|
_uploadsLast90Days = snapshot.UploadsLast90Days;
|
|
_hasSnapshot = true;
|
|
|
|
OnPropertyChanged(nameof(DisplayName));
|
|
OnPropertyChanged(nameof(SubscriberCount));
|
|
OnPropertyChanged(nameof(VideoCount));
|
|
OnPropertyChanged(nameof(TotalViews));
|
|
OnPropertyChanged(nameof(UploadsLast90Days));
|
|
OnPropertyChanged(nameof(HasSnapshot));
|
|
OnPropertyChanged(nameof(Tier1SubsProgress));
|
|
OnPropertyChanged(nameof(Tier2SubsProgress));
|
|
OnPropertyChanged(nameof(UploadsProgress));
|
|
OnPropertyChanged(nameof(Tier1SubsBarWidth));
|
|
OnPropertyChanged(nameof(Tier2SubsBarWidth));
|
|
OnPropertyChanged(nameof(UploadsBarWidth));
|
|
OnPropertyChanged(nameof(Tier1SubsText));
|
|
OnPropertyChanged(nameof(Tier2SubsText));
|
|
OnPropertyChanged(nameof(UploadsText));
|
|
OnPropertyChanged(nameof(StandingDetailText));
|
|
}
|
|
|
|
private void PersistChecklist() => _store().SaveYppChecklist(TwoFactorEnabled, AdSenseLinked);
|
|
|
|
private static double Progress(long current, long target)
|
|
=> target <= 0 ? 0 : Math.Clamp((double)current / target, 0, 1);
|
|
|
|
private static void OpenUrl(string url)
|
|
{
|
|
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
|
|
}
|
|
} |