Initial scaffold: ytLive C# WPF project

- MVVM architecture (Models, ViewModels, Views, Services, Helpers)
- Models: Scene, Source, StreamConfig, StreamHealth, YouTubeChannel, ChatMessage
- Services: YouTubeAuthService (OAuth2), YouTubeStreamService (broadcasts/stream health),
  YouTubeChatService (live chat polling)
- ViewModels: MainViewModel with scene management, stream controls, chat
- MainWindow with dark theme: scene/source panel, preview area, chat panel, status bar
- Version roadmap: v0.1 (scenes, RTMP, OAuth2, chat, health) -> 1.0
This commit is contained in:
2026-08-04 09:09:52 -07:00
commit 9103ff1fb7
16 changed files with 943 additions and 0 deletions
+118
View File
@@ -0,0 +1,118 @@
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using ytLive.Models;
namespace ytLive.Services;
/// <summary>
/// Handles YouTube OAuth2 authentication flow.
/// Uses a local HTTP listener for the redirect callback.
/// </summary>
public class YouTubeAuthService
{
private const string AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/v2/auth";
private const string TokenEndpoint = "https://oauth2.googleapis.com/token";
private const string Scope = "https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.force-ssl";
private readonly string _clientId;
private readonly string _clientSecret;
private readonly HttpClient _http = new();
public YouTubeChannel? CurrentChannel { get; private set; }
public YouTubeAuthService(string clientId, string clientSecret)
{
_clientId = clientId;
_clientSecret = clientSecret;
}
public string GetAuthorizationUrl(string redirectUri)
{
var parameters = HttpUtility.ParseQueryString(string.Empty);
parameters["client_id"] = _clientId;
parameters["redirect_uri"] = redirectUri;
parameters["response_type"] = "code";
parameters["scope"] = Scope;
parameters["access_type"] = "offline";
parameters["prompt"] = "consent";
return $"{AuthorizationEndpoint}?{parameters}";
}
public async Task<YouTubeChannel?> ExchangeCodeForToken(string code, string redirectUri)
{
var body = new FormUrlEncodedContent(new Dictionary<string, string>
{
["code"] = code,
["client_id"] = _clientId,
["client_secret"] = _clientSecret,
["redirect_uri"] = redirectUri,
["grant_type"] = "authorization_code"
});
var response = await _http.PostAsync(TokenEndpoint, body);
if (!response.IsSuccessStatusCode)
return null;
var json = await response.Content.ReadAsStringAsync();
var tokenData = JsonSerializer.Deserialize<JsonElement>(json);
var accessToken = tokenData.GetProperty("access_token").GetString()!;
var refreshToken = tokenData.GetProperty("refresh_token").GetString()!;
var expiresIn = tokenData.GetProperty("expires_in").GetInt32();
// Fetch channel info
return await FetchChannelInfo(accessToken, refreshToken, expiresIn);
}
public async Task<bool> RefreshToken()
{
if (CurrentChannel == null) return false;
var body = new FormUrlEncodedContent(new Dictionary<string, string>
{
["refresh_token"] = CurrentChannel.RefreshToken,
["client_id"] = _clientId,
["client_secret"] = _clientSecret,
["grant_type"] = "refresh_token"
});
var response = await _http.PostAsync(TokenEndpoint, body);
if (!response.IsSuccessStatusCode) return false;
var json = await response.Content.ReadAsStringAsync();
var tokenData = JsonSerializer.Deserialize<JsonElement>(json);
CurrentChannel.AccessToken = tokenData.GetProperty("access_token").GetString()!;
CurrentChannel.TokenExpiry = DateTime.UtcNow.AddSeconds(tokenData.GetProperty("expires_in").GetInt32());
return true;
}
private async Task<YouTubeChannel?> FetchChannelInfo(string accessToken, string refreshToken, int expiresIn)
{
_http.DefaultRequestHeaders.Authorization = new("Bearer", accessToken);
var response = await _http.GetAsync("https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true");
if (!response.IsSuccessStatusCode) return null;
var json = await response.Content.ReadAsStringAsync();
var data = JsonSerializer.Deserialize<JsonElement>(json);
var items = data.GetProperty("items");
if (items.GetArrayLength() == 0) return null;
var snippet = items[0].GetProperty("snippet");
CurrentChannel = new YouTubeChannel
{
ChannelId = items[0].GetProperty("id").GetString()!,
DisplayName = snippet.GetProperty("title").GetString()!,
ProfileImageUrl = snippet.GetProperty("thumbnails").GetProperty("default").GetProperty("url").GetString()!,
AccessToken = accessToken,
RefreshToken = refreshToken,
TokenExpiry = DateTime.UtcNow.AddSeconds(expiresIn)
};
return CurrentChannel;
}
}
+102
View File
@@ -0,0 +1,102 @@
using System.Net.Http;
using System.Text.Json;
using ytLive.Models;
namespace ytLive.Services;
/// <summary>
/// Polls YouTube Live Chat API for messages.
/// YouTube doesn't have WebSocket for chat — polling is the only option.
/// </summary>
public class YouTubeChatService : IDisposable
{
private readonly YouTubeAuthService _auth;
private readonly HttpClient _http = new();
private Timer? _pollTimer;
private string? _nextPageToken;
private string? _liveChatId;
private bool _isRunning;
public event Action<ChatMessage>? MessageReceived;
private static readonly JsonSerializerOptions JsonOpts = new()
{
PropertyNameCaseInsensitive = true
};
public YouTubeChatService(YouTubeAuthService auth)
{
_auth = auth;
}
public void Start(string liveChatId, int pollIntervalMs = 2000)
{
_liveChatId = liveChatId;
_isRunning = true;
_nextPageToken = null;
_pollTimer = new(async _ => await Poll(), null, 0, pollIntervalMs);
}
public void Stop()
{
_isRunning = false;
_pollTimer?.Dispose();
_pollTimer = null;
}
private async Task Poll()
{
if (!_isRunning || _liveChatId == null || _auth.CurrentChannel == null) return;
try
{
if (_auth.CurrentChannel.TokenExpiry <= DateTime.UtcNow.AddMinutes(5))
await _auth.RefreshToken();
var url = $"https://www.googleapis.com/youtube/v3/liveChat/messages?liveChatId={_liveChatId}&part=snippet,authorDetails&maxResults=50";
if (_nextPageToken != null)
url += $"&pageToken={_nextPageToken}";
_http.DefaultRequestHeaders.Authorization = new("Bearer", _auth.CurrentChannel.AccessToken);
var response = await _http.GetAsync(url);
if (!response.IsSuccessStatusCode) return;
var json = await response.Content.ReadAsStringAsync();
var data = JsonSerializer.Deserialize<JsonElement>(json);
if (data.TryGetProperty("nextPageToken", out var token))
_nextPageToken = token.GetString();
if (!data.TryGetProperty("items", out var items)) return;
foreach (var item in items.EnumerateArray())
{
var snippet = item.GetProperty("snippet");
var author = item.GetProperty("authorDetails");
var message = new ChatMessage
{
Id = item.GetProperty("id").GetString()!,
AuthorName = author.GetProperty("displayName").GetString()!,
AuthorChannelId = author.GetProperty("channelId").GetString()!,
AuthorImageUrl = author.GetProperty("profileImageUrl").GetString()!,
Message = snippet.GetProperty("textMessageDetails").GetProperty("messageText").GetString()!,
Timestamp = DateTime.Parse(snippet.GetProperty("publishedAt").GetString()!),
IsMember = author.GetProperty("isChatSponsor").GetBoolean()
};
MessageReceived?.Invoke(message);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Chat poll error: {ex.Message}");
}
}
public void Dispose()
{
Stop();
_http.Dispose();
}
}
+129
View File
@@ -0,0 +1,129 @@
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using ytLive.Models;
namespace ytLive.Services;
/// <summary>
/// Manages YouTube live stream lifecycle — create broadcasts,
/// bind stream keys, monitor health.
/// </summary>
public class YouTubeStreamService
{
private readonly YouTubeAuthService _auth;
private readonly HttpClient _http = new();
private const string ApiBase = "https://www.googleapis.com/youtube/v3";
public YouTubeStreamService(YouTubeAuthService auth)
{
_auth = auth;
}
private async Task<bool> EnsureToken()
{
if (_auth.CurrentChannel == null) return false;
if (_auth.CurrentChannel.TokenExpiry <= DateTime.UtcNow.AddMinutes(5))
return await _auth.RefreshToken();
return true;
}
public async Task<string?> CreateBroadcast(string title, string description, DateTime scheduledStartTime)
{
if (!await EnsureToken()) return null;
var broadcast = new
{
snippet = new
{
title,
description,
scheduledStartTime = scheduledStartTime.ToString("o"),
categoryId = "22" // People & Blogs
},
status = new
{
privacyStatus = "public",
selfDeclaredMadeForKids = false
},
contentDetails = new
{
enableAutoStart = true,
enableAutoStop = true
}
};
_http.DefaultRequestHeaders.Authorization = new("Bearer", _auth.CurrentChannel!.AccessToken);
var response = await _http.PostAsJsonAsync(
$"{ApiBase}/liveBroadcasts?part=snippet,status,contentDetails", broadcast);
if (!response.IsSuccessStatusCode) return null;
var json = await response.Content.ReadAsStringAsync();
var data = JsonSerializer.Deserialize<JsonElement>(json);
return data.GetProperty("id").GetString();
}
public async Task<string?> BindStream(string broadcastId, string streamKey)
{
if (!await EnsureToken()) return null;
// Create stream resource
var stream = new
{
snippet = new { title = $"stream-{broadcastId}" },
contentDetails = new
{
ingestionType = "rtmp",
frameRate = "60fps",
resolution = "1080p"
}
};
_http.DefaultRequestHeaders.Authorization = new("Bearer", _auth.CurrentChannel!.AccessToken);
var response = await _http.PostAsJsonAsync(
$"{ApiBase}/liveStreams?part=snippet,contentDetails", stream);
if (!response.IsSuccessStatusCode) return null;
var json = await response.Content.ReadAsStringAsync();
var data = JsonSerializer.Deserialize<JsonElement>(json);
var streamId = data.GetProperty("id").GetString();
// Bind stream to broadcast
var bindResponse = await _http.PutAsJsonAsync(
$"{ApiBase}/liveBroadcasts?part=id,contentDetails&id={broadcastId}",
new { contentDetails = new { streamId } });
return bindResponse.IsSuccessStatusCode ? streamId : null;
}
public async Task<StreamHealth?> GetStreamHealth(string broadcastId)
{
if (!await EnsureToken()) return null;
_http.DefaultRequestHeaders.Authorization = new("Bearer", _auth.CurrentChannel!.AccessToken);
var response = await _http.GetAsync(
$"{ApiBase}/liveBroadcasts?part=contentDetails,status&id={broadcastId}");
if (!response.IsSuccessStatusCode) return null;
var json = await response.Content.ReadAsStringAsync();
var data = JsonSerializer.Deserialize<JsonElement>(json);
var items = data.GetProperty("items");
if (items.GetArrayLength() == 0) return null;
var status = items[0].GetProperty("status").GetProperty("lifeCycleStatus").GetString();
return new StreamHealth
{
HealthStatus = status switch
{
"live" => "good",
"ready" => "ok",
"created" => "ok",
_ => "bad"
},
HealthMessage = status
};
}
}