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
+9
View File
@@ -0,0 +1,9 @@
<Application x:Class="ytLive.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ytLive"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
+13
View File
@@ -0,0 +1,13 @@
using System.Configuration;
using System.Data;
using System.Windows;
namespace ytLive;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
+10
View File
@@ -0,0 +1,10 @@
using System.Windows;
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
+24
View File
@@ -0,0 +1,24 @@
using System.Windows.Input;
namespace ytLive.Helpers;
public class RelayCommand : ICommand
{
private readonly Action<object?> _execute;
private readonly Func<object?, bool>? _canExecute;
public RelayCommand(Action<object?> execute, Func<object?, bool>? canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler? CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public bool CanExecute(object? parameter) => _canExecute?.Invoke(parameter) ?? true;
public void Execute(object? parameter) => _execute(parameter);
}
+23
View File
@@ -0,0 +1,23 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace ytLive.Helpers;
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
+242
View File
@@ -0,0 +1,242 @@
<Window x:Class="ytLive.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:ytLive.ViewModels"
mc:Ignorable="d"
Title="ytLive" Height="720" Width="1280"
Background="#1a1a2e"
WindowStartupLocation="CenterScreen">
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis"/>
<!-- Base button style -->
<Style x:Key="YtButton" TargetType="Button">
<Setter Property="Background" Value="#e94560"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Padding" Value="16,8"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}"
CornerRadius="4"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="YtButtonSecondary" TargetType="Button" BasedOn="{StaticResource YtButton}">
<Setter Property="Background" Value="#16213e"/>
</Style>
<Style x:Key="YtTextBox" TargetType="TextBox">
<Setter Property="Background" Value="#0f3460"/>
<Setter Property="Foreground" Value="#e0e0e0"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="8,6"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="CaretBrush" Value="White"/>
</Style>
<Style x:Key="YtLabel" TargetType="TextBlock">
<Setter Property="Foreground" Value="#a0a0b0"/>
<Setter Property="FontSize" Value="12"/>
</Style>
<Style x:Key="SectionHeader" TargetType="TextBlock">
<Setter Property="Foreground" Value="#e0e0e0"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Margin" Value="0,0,0,8"/>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- ═══ TOP BAR: Stream Controls ═══ -->
<Border Grid.Row="0" Background="#16213e" Padding="16,10">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!-- Logo / Brand -->
<TextBlock Grid.Column="0" Text="ytLive"
Foreground="#e94560" FontSize="22" FontWeight="Bold"
VerticalAlignment="Center" Margin="0,0,24,0"/>
<!-- Stream Title -->
<TextBox Grid.Column="1" Style="{StaticResource YtTextBox}"
Text="{Binding StreamTitle, UpdateSourceTrigger=PropertyChanged}"
Width="400" HorizontalAlignment="Left"
VerticalAlignment="Center"/>
<!-- Stream Status -->
<Border Grid.Column="2" Background="#0f3460" CornerRadius="4"
Padding="12,6" Margin="16,0" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal">
<Ellipse Width="10" Height="10" Margin="0,0,8,0">
<Ellipse.Style>
<Style TargetType="Ellipse">
<Setter Property="Fill" Value="#555"/>
<Style.Triggers>
<DataTrigger Binding="{Binding StreamStatus}" Value="Streaming">
<Setter Property="Fill" Value="#00ff00"/>
</DataTrigger>
<DataTrigger Binding="{Binding StreamStatus}" Value="Connecting">
<Setter Property="Fill" Value="#ffaa00"/>
</DataTrigger>
<DataTrigger Binding="{Binding StreamStatus}" Value="Error">
<Setter Property="Fill" Value="#ff0000"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Ellipse.Style>
</Ellipse>
<TextBlock Text="{Binding StatusDisplay}" Foreground="White"
FontSize="13" FontWeight="SemiBold" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<!-- Stream Controls -->
<StackPanel Grid.Column="3" Orientation="Horizontal" VerticalAlignment="Center">
<Button Content="▶ GO LIVE" Style="{StaticResource YtButton}"
Command="{Binding StartStreamCommand}"
Visibility="{Binding StreamStatus, Converter={StaticResource BoolToVis},
ConverterParameter=Offline}"/>
<Button Content="■ STOP" Style="{StaticResource YtButton}"
Background="#333" Command="{Binding StopStreamCommand}"/>
<Button Content="YouTube" Style="{StaticResource YtButtonSecondary}"
Command="{Binding ConnectYouTubeCommand}" Margin="8,0,0,0"/>
</StackPanel>
</Grid>
</Border>
<!-- ═══ MIDDLE: Main Content ═══ -->
<Grid Grid.Row="1" Margin="8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="220"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="300"/>
</Grid.ColumnDefinitions>
<!-- LEFT PANEL: Scenes & Sources -->
<Border Grid.Column="0" Background="#16213e" CornerRadius="6" Padding="12">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Scenes -->
<TextBlock Grid.Row="0" Text="SCENES" Style="{StaticResource SectionHeader}"/>
<ListBox Grid.Row="1" Background="Transparent" BorderThickness="0"
ItemsSource="{Binding Scenes}"
SelectedItem="{Binding ActiveScene}"
Foreground="#e0e0e0" FontSize="13">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Padding="4,4"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0,8,0,0">
<Button Content="+" Style="{StaticResource YtButtonSecondary}"
Command="{Binding AddSceneCommand}" Padding="8,4" Margin="0,0,4,0"/>
<Button Content="" Style="{StaticResource YtButtonSecondary}"
Command="{Binding RemoveSceneCommand}" Padding="8,4"/>
</StackPanel>
<!-- Sources (for active scene) -->
<TextBlock Grid.Row="3" Text="SOURCES" Style="{StaticResource SectionHeader}" Margin="0,12,0,0"/>
</Grid>
</Border>
<!-- CENTER: Preview Area -->
<Border Grid.Column="1" Background="#0a0a1a" CornerRadius="6" Margin="8,0">
<Grid>
<TextBlock Text="Preview" Foreground="#333" FontSize="24"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<!-- TODO: D3DImage or MediaElement for video preview -->
</Grid>
</Border>
<!-- RIGHT PANEL: Chat -->
<Border Grid.Column="2" Background="#16213e" CornerRadius="6" Padding="12">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="LIVE CHAT" Style="{StaticResource SectionHeader}"/>
<ListBox Grid.Row="1" Background="Transparent" BorderThickness="0"
ItemsSource="{Binding ChatMessages}"
Foreground="#e0e0e0" FontSize="12">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,2">
<TextBlock>
<Run Text="{Binding AuthorName, Mode=OneWay}" FontWeight="Bold" Foreground="#e94560"/>
<Run Text=": "/>
<Run Text="{Binding Message, Mode=OneWay}" Foreground="#e0e0e0"/>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
</Grid>
<!-- ═══ BOTTOM BAR: Stream Health ═══ -->
<Border Grid.Row="2" Background="#0f3460" Padding="16,6">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Bitrate:" Style="{StaticResource YtLabel}" Margin="0,0,4,0"/>
<TextBlock Text="{Binding CurrentHealth.CurrentBitrate}" Style="{StaticResource YtLabel}"
Foreground="White" Margin="0,0,20,0"/>
<TextBlock Text="FPS:" Style="{StaticResource YtLabel}" Margin="0,0,4,0"/>
<TextBlock Text="{Binding CurrentHealth.FPS}" Style="{StaticResource YtLabel}"
Foreground="White" Margin="0,0,20,0"/>
<TextBlock Text="Dropped:" Style="{StaticResource YtLabel}" Margin="0,0,4,0"/>
<TextBlock Text="{Binding CurrentHealth.DroppedFrames}" Style="{StaticResource YtLabel}"
Foreground="White" Margin="0,0,20,0"/>
<TextBlock Text="Duration:" Style="{StaticResource YtLabel}" Margin="0,0,4,0"/>
<TextBlock Text="{Binding CurrentHealth.StreamDuration}" Style="{StaticResource YtLabel}"
Foreground="White"/>
<TextBlock Text="{Binding CurrentHealth.HealthMessage}" Style="{StaticResource YtLabel}"
Foreground="#e94560" Margin="20,0,0,0"/>
</StackPanel>
</Border>
</Grid>
</Window>
+11
View File
@@ -0,0 +1,11 @@
using System.Windows;
namespace ytLive;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace ytLive.Models;
public class Scene
{
public string Id { get; init; } = Guid.NewGuid().ToString();
public string Name { get; set; } = string.Empty;
public List<Source> Sources { get; set; } = new();
}
+35
View File
@@ -0,0 +1,35 @@
namespace ytLive.Models;
public enum SourceType
{
DisplayCapture,
WindowCapture,
Webcam,
Image,
TextOverlay
}
public class Source
{
public string Id { get; init; } = Guid.NewGuid().ToString();
public string Name { get; set; } = string.Empty;
public SourceType Type { get; set; }
public bool IsEnabled { get; set; } = true;
// Display/Window capture
public int? MonitorIndex { get; set; }
public IntPtr? WindowHandle { get; set; }
// Webcam
public string? DeviceId { get; set; }
// Image
public string? FilePath { get; set; }
// Position/transform
public double X { get; set; }
public double Y { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public double Opacity { get; set; } = 1.0;
}
+35
View File
@@ -0,0 +1,35 @@
namespace ytLive.Models;
public enum StreamStatus
{
Offline,
Connecting,
Streaming,
Error
}
public class StreamConfig
{
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string StreamKey { get; set; } = string.Empty;
public string IngestUrl { get; set; } = "rtmp://a.rtmp.youtube.com/live2";
public bool IsLowLatency { get; set; } = true;
public int TargetBitrate { get; set; } = 6000;
public int TargetFps { get; set; } = 60;
public string Resolution { get; set; } = "1920x1080";
}
public class StreamHealth
{
public StreamStatus Status { get; set; }
public double CurrentBitrate { get; set; }
public int DroppedFrames { get; set; }
public double FPS { get; set; }
public TimeSpan StreamDuration { get; set; }
public string? LastError { get; set; }
// YouTube-specific
public string? HealthStatus { get; set; } // "good", "bad", "ok"
public string? HealthMessage { get; set; }
}
+26
View File
@@ -0,0 +1,26 @@
namespace ytLive.Models;
public class YouTubeChannel
{
public string ChannelId { get; set; } = string.Empty;
public string DisplayName { get; set; } = string.Empty;
public string ProfileImageUrl { get; set; } = string.Empty;
public string AccessToken { get; set; } = string.Empty;
public string RefreshToken { get; set; } = string.Empty;
public DateTime TokenExpiry { get; set; }
}
public class ChatMessage
{
public string Id { get; init; } = Guid.NewGuid().ToString();
public string AuthorName { get; set; } = string.Empty;
public string AuthorChannelId { get; set; } = string.Empty;
public string AuthorImageUrl { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
public DateTime Timestamp { get; set; }
public bool IsSuperChat { get; set; }
public double SuperChatAmount { get; set; }
public string? SuperChatCurrency { get; set; }
public bool IsMember { get; set; }
public string? MembershipLevel { get; set; }
}
+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
};
}
}
+143
View File
@@ -0,0 +1,143 @@
using System.Collections.ObjectModel;
using System.Windows.Input;
using ytLive.Helpers;
using ytLive.Models;
using ytLive.Services;
namespace ytLive.ViewModels;
public class MainViewModel : ViewModelBase
{
private readonly YouTubeAuthService _youtubeAuth;
private readonly YouTubeStreamService _youtubeStream;
private readonly YouTubeChatService _youtubeChat;
private Scene? _activeScene;
private StreamStatus _streamStatus = StreamStatus.Offline;
private StreamHealth _currentHealth = new();
private string _streamTitle = string.Empty;
private string _streamKey = string.Empty;
private bool _isYouTubeConnected;
public ObservableCollection<Scene> Scenes { get; } = new();
public ObservableCollection<ChatMessage> ChatMessages { get; } = new();
public Scene? ActiveScene
{
get => _activeScene;
set => SetProperty(ref _activeScene, value);
}
public StreamStatus StreamStatus
{
get => _streamStatus;
set => SetProperty(ref _streamStatus, value);
}
public StreamHealth CurrentHealth
{
get => _currentHealth;
set => SetProperty(ref _currentHealth, value);
}
public string StreamTitle
{
get => _streamTitle;
set => SetProperty(ref _streamTitle, value);
}
public string StreamKey
{
get => _streamKey;
set => SetProperty(ref _streamKey, value);
}
public bool IsYouTubeConnected
{
get => _isYouTubeConnected;
set => SetProperty(ref _isYouTubeConnected, value);
}
public string StatusDisplay => StreamStatus switch
{
StreamStatus.Offline => "OFFLINE",
StreamStatus.Connecting => "CONNECTING...",
StreamStatus.Streaming => "LIVE",
StreamStatus.Error => "ERROR",
_ => "UNKNOWN"
};
// Commands
public ICommand AddSceneCommand { get; }
public ICommand RemoveSceneCommand { get; }
public ICommand StartStreamCommand { get; }
public ICommand StopStreamCommand { get; }
public ICommand ConnectYouTubeCommand { get; }
public MainViewModel()
{
_youtubeAuth = new YouTubeAuthService("", ""); // TODO: load from config
_youtubeStream = new YouTubeStreamService(_youtubeAuth);
_youtubeChat = new YouTubeChatService(_youtubeAuth);
_youtubeChat.MessageReceived += OnChatMessageReceived;
AddSceneCommand = new RelayCommand(_ => AddScene());
RemoveSceneCommand = new RelayCommand(scene => RemoveScene(scene as Scene));
StartStreamCommand = new RelayCommand(_ => StartStream(), _ => StreamStatus == StreamStatus.Offline);
StopStreamCommand = new RelayCommand(_ => StopStream(), _ => StreamStatus == StreamStatus.Streaming);
ConnectYouTubeCommand = new RelayCommand(_ => ConnectYouTube());
// Start with a default scene
AddScene("Scene 1");
}
private void AddScene(string? name = null)
{
var scene = new Scene { Name = name ?? $"Scene {Scenes.Count + 1}" };
Scenes.Add(scene);
ActiveScene = scene;
}
private void RemoveScene(Scene? scene)
{
if (scene == null) return;
Scenes.Remove(scene);
if (ActiveScene == scene)
ActiveScene = Scenes.FirstOrDefault();
}
private void OnChatMessageReceived(ChatMessage message)
{
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
ChatMessages.Add(message);
if (ChatMessages.Count > 500)
ChatMessages.RemoveAt(0);
});
}
private async void StartStream()
{
StreamStatus = StreamStatus.Connecting;
OnPropertyChanged(nameof(StatusDisplay));
// TODO: Initialize capture pipeline, encode, and push to RTMP
// For now, simulate connection
StreamStatus = StreamStatus.Streaming;
OnPropertyChanged(nameof(StatusDisplay));
}
private void StopStream()
{
StreamStatus = StreamStatus.Offline;
OnPropertyChanged(nameof(StatusDisplay));
}
private void ConnectYouTube()
{
// TODO: Launch OAuth2 flow in browser
// For now, this is a stub
IsYouTubeConnected = false;
}
}
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<ApplicationIcon></ApplicationIcon>
<AssemblyName>ytLive</AssemblyName>
<RootNamespace>ytLive</RootNamespace>
</PropertyGroup>
</Project>