feat: LD KickWatch v1.2.0 - Full Studio Release (Embedded VLC, Multi-Stream 2x2, Split Chat, Kick Emotes, Audio & Keyword Alerts)

This commit is contained in:
LilDosto 2026-10-27 22:11:06 +03:00
commit acce34e346
35 changed files with 5857 additions and 0 deletions

30
.gitignore vendored Normal file
View file

@ -0,0 +1,30 @@
## .NET / Visual Studio Build Outputs
[Bb]in/
[Oo]bj/
[Dd]ebug/
[Rr]elease/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Ll]og/
[Ll]ogs/
## Visual Studio / Rider / VS Code
.vs/
.idea/
.vscode/
*.suo
*.user
*.userosscache
*.sln.docstates
*.DotSettings.user
## Temporary & Crash Dumps
*.tmp
*.bak
*.dmp
*.pdb
*.xml
publish_small/

22
KickStreamHub.sln Normal file
View file

@ -0,0 +1,22 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.0.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KickStreamHub", "src\KickStreamHub\KickStreamHub.csproj", "{2E1D1A6D-2C0A-4E2B-9C34-1B7C6B6E9B10}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2E1D1A6D-2C0A-4E2B-9C34-1B7C6B6E9B10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E1D1A6D-2C0A-4E2B-9C34-1B7C6B6E9B10}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2E1D1A6D-2C0A-4E2B-9C34-1B7C6B6E9B10}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E1D1A6D-2C0A-4E2B-9C34-1B7C6B6E9B10}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 LilDosto
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

132
README.md Normal file
View file

@ -0,0 +1,132 @@
<div align="center">
# 🟢 LD KickWatch
**Kick.com için Modern Masaüstü Canlı Yayın İzleme Stüdyosu ve Sohbet İstemcisi**
[![Platform](https://img.shields.io/badge/Platform-Windows%2010%20%2F%2011%20(x64)-0078D6?style=for-the-badge&logo=windows)](https://github.com/LilDosto/LD-KickWatch)
[![.NET](https://img.shields.io/badge/.NET-8.0%20WPF-512BD4?style=for-the-badge&logo=dotnet)](https://dotnet.microsoft.com/download/dotnet/8.0)
[![License](https://img.shields.io/badge/Lisans-MIT-53FC18?style=for-the-badge)](./LICENSE)
Favori **Kick.com** yayıncılarınızı takip edin, anlık canlı yayın ve kategori bildirimleri alın, **Pencere İçi Web Oynatıcı (WebView2)** veya **Pencere İçi Gömülü VLC** ile yayınları izleyin, **2x2 Çoklu Yayın (Squad View)** modunda 4 yayını aynı anda takip edin ve gerçek **Kick Emote** destekli canlı sohbete bağlanın.
[📦 **Tek Dosya İndir (`LDKickWatch.exe`)**](./publish/LDKickWatch.exe) • [🚀 **Özellikler**](#-başlıca-özellikler) • [⌨ **Kısayollar**](#-klavye-kısayolları) • [🛠 **Derleme**](#-kaynak-koddan-derleme)
</div>
---
## 🚀 Başlıca Özellikler
### 🎬 Gelişmiş Çift Oynatıcı Motoru (Pencere İçi Web & Pencere İçi VLC)
- **🌐 Dahili Modern Web Oynatıcı (WebView2):** Ekstra hiçbir programa ihtiyaç duymadan yayınları doğrudan uygulama içinde açar.
- **🎬 Pencere İçi Gömülü VLC (`--drawable-hwnd`):** VLC Media Player'ı ayrı bir pencere açmadan doğrudan uygulama arayüzünün içine gömer. Streamlink kurulu olmasa bile Kick API'den alınan doğrudan HLS (`playback_url`) akışı ile çalışır.
- **⚡ Tek Tıkla Motor Değiştirme:** Yayını izlerken üst kontrol barındaki **🌐 Web** ve **🎬 VLC (Pencere İçi)** butonlarıyla anında oynatıcı motorları arasında geçiş yapabilirsiniz.
- **🚀 Harici VLC & MPV Desteği:** İsterseniz Streamlink üzerinden harici VLC veya MPV penceresinde `best`, `1080p60`, `720p60`, `480p`, `360p`, `160p` ve `audio_only` kalitelerinde izleyebilirsiniz.
### ⛶ Gerçek Tam Ekran & Sinema Modu
- **Tam Ekran (`F11` / `Esc` / Çift Tıklama):** Hem oynatıcı barındaki **⛶ Tam Ekran** butonu, hem `F11` kısayolu, hem VLC paneline çift tıklama hem de Kick oynatıcısının içindeki tam ekran butonu (`ContainsFullScreenElementChanged`) tam senkronize çalışır.
- **Sinema Modu (`🗖`):** Pencereyi tam ekran yapmadan sağ panelin tamamını video oynatıcıya ayırır.
- **Bağımsız Pencere & PiP (`📌 Üstte Tut`):** Yayını ayrı bir pencerede açıp her zaman üstte (Picture-in-Picture tarzı) sabitleyebilirsiniz.
### ⊞ 2x2 Çoklu Yayın Stüdyosu (Multi-Stream / Squad View)
- Sol menüdeki **⊞ Çoklu Yayın** sekmesinden aynı anda **4 canlı yayını (2x2 Izgara)** veya **2 canlı yayını (Yan Yana)** izleyebilirsiniz.
- **⚡ Canlı Kanalları Otomatik Doldur:** O an yayında olan favori kanallarınızı tek tıkla 4 ekrana otomatik yerleştirir.
- **🔊 Tek Tıkla Ses Odaklama (Solo Audio):** İstediğiniz ekranın **🔊 Bu Ekranı Dinle** butonuna tıkladığınızda o yayının sesi açılır, diğer 3 ekran otomatik olarak sessize alınır.
### 💬 Yerleşik (Split-View) Sohbet Çekmecesi & Görsel Kick Emote Desteği
- **Yan Sohbet Çekmecesi:** Ana pencerenin sağ tarafında (Sinema Modu ve Tam Ekran dahil) açılıp kapanabilen yerleşik canlı sohbet paneli.
- **Bağımsız Sohbet Penceresi:** Saydamlık (Opacity), yazı boyutu ve **📌 Üstte Tut** ayarlarına sahip harici sohbet penceresi.
- **😎 Gerçek Kick Emote Render Sistemi:** Pusher WebSocket üzerinden gelen `[emote:ID:Name]` ifadeleri asenkron olarak indirilip bellek içi önbelleğe (`EmoteCache`) alınır ve sohbette gerçek görsel ifadeler olarak gösterilir.
### 🔔 Sesli Bildirimler, Kategori Değişikliği ve Anahtar Kelime Uyarıları
- **Canlı Yayın Bildirimi:** Takip ettiğiniz yayıncı yayına girdiğinde masaüstü bildirimi ve yerleşik çift tonlu armonik bildirim zili (veya seçtiğiniz özel `.wav` sesi) çalar.
- **🎮 Kategori / Oyun Değişikliği Uyarısı:** Yayıncı yayındayken oynadığı oyunu veya kategoriyi değiştirdiğinde anında bildirim verir.
- **🎯 Anahtar Kelime Yakalayıcı:** Belirlediğiniz kelimeler (örn: `çekiliş, turnuva, valorant, derbi`) yayın başlığında veya kategorisinde geçtiğinde özel sesli ve görsel uyarı gönderir.
### 🏷 Favori Gruplama / Etiketleme ve JSON/CSV Yedekleme
- Kanallara özel grup etiketleri (`FPS`, `IRL`, `E-Spor`, `Favoriler` vb.) atayabilir ve sol panelden gruba göre filtreleyebilirsiniz.
- **📤 Dışa Aktar / 📥 İçe Aktar:** Takip listenizi ve grup etiketlerinizi `.json` veya `.csv` formatında yedekleyebilir veya geri yükleyebilirsiniz.
- **⚡ Toplu Kanal Ekleme:** Virgül veya boşlukla ayrılmış birden fazla kanal adını ya da `kick.com/kanal` bağlantısını tek seferde ekleyebilirsiniz.
---
## 📥 Kurulum ve Kullanım
### Seçenek 1: Hazır Tek Dosya İle Çalıştırma (Önerilen)
1. Bu depodaki [`publish/LDKickWatch.exe`](./publish/LDKickWatch.exe) dosyasını indirin.
2. Çift tıklayarak doğrudan çalıştırın (`.NET Runtime` dahil tüm bağımlılıklar tek `.exe` içine gömülüdür, kurulum gerektirmez).
### Seçenek 2: Kaynak Koddan Derleme
Gereksinimler: [.NET 8.0 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) (Windows)
```powershell
git clone https://github.com/LilDosto/LD-KickWatch.git
cd LD-KickWatch
# Geliştirme modunda çalıştırma
dotnet run --project src/KickStreamHub/KickStreamHub.csproj
# Sıkıştırılmış bağımsız tek dosya (.exe) olarak derleme
dotnet publish src/KickStreamHub/KickStreamHub.csproj -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true -p:DebugType=none -p:DebugSymbols=false -o publish
```
---
## ⌨ Klavye Kısayolları
| Kısayol | İşlev |
| :--- | :--- |
| **`F11`** / **`Esc`** | Oynatıcıyı Tam Ekran yap / Tam ekrandan çık |
| **`F5`** | Tüm kanalların canlı yayın durumunu anında yenile |
| **`Ctrl + F`** | Kanal, başlık, kategori ve grup arama kutusuna odaklan |
| **`Çift Tıklama`** | Kanal listesindeki yayıncıyı başlat / VLC panelinde tam ekrana geç |
| **`Enter`** | Kanal ekleme veya grup etiketi kutusundaki işlemi onayla |
| **`Ctrl + Q`** | Uygulamadan tamamen çık |
---
## 🏗 Proje Mimarisi
```text
LD-KickWatch/
├── publish/
│ └── LDKickWatch.exe # Bağımsız tek dosya (Self-Contained) Windows sürümü
├── src/KickStreamHub/
│ ├── Helpers/
│ │ └── RichChatHelper.cs # Görsel Kick Emote ayrıştırıcı ve bellek önbelleği
│ ├── Models/
│ │ ├── AppConfig.cs # Kullanıcı tercihleri ve grup modelleri
│ │ ├── ChannelStatus.cs # Canlı yayın, izleyici ve HLS akış durumu
│ │ └── KickApiModels.cs # Kick API v1/v2 JSON DTO modelleri
│ ├── Services/
│ │ ├── KickApiService.cs # Thread-safe HTTP/2 Kick API istemcisi
│ │ ├── LiveStatusPollingService.cs# Eşzamanlı (SemaphoreSlim) periyodik durum sorgulayıcı
│ │ ├── PusherChatService.cs # Otomatik yeniden bağlanan Pusher WebSocket istemcisi
│ │ ├── StreamlinkService.cs # Pencere içi gömülü VLC (--drawable-hwnd) & harici oynatıcı servisi
│ │ ├── SoundService.cs # PCM WAV sentezleyici ve özel ses bildirim servisi
│ │ ├── AvatarCacheService.cs # Dosya kilitlemeyen yerel profil resmi önbelleği
│ │ ├── ConfigService.cs # %LOCALAPPDATA%\LDKickWatch JSON yapılandırma yöneticisi
│ │ ├── NotificationService.cs # Sistem tepsisi (System Tray) ve masaüstü bildirimleri
│ │ ├── StartupService.cs # Windows başlangıç (Registry) entegrasyonu
│ │ └── LoggingService.cs # Otomatik rotasyonlu (5 MB) log servisi
│ ├── ViewModels/
│ │ ├── MainViewModel.cs # Ana stüdyo, filtreleme, bildirim ve çoklu yayın mantığı
│ │ ├── ChannelCardViewModel.cs # Kanal kartı görünüm modeli
│ │ ├── ChatViewModel.cs # Yerleşik ve harici sohbet görünüm modeli
│ │ └── MultiStreamSlotViewModel.cs# 2x2 Squad View ekran modeli
│ ├── Views/
│ │ ├── MainWindow.xaml(.cs) # Ana uygulama penceresi
│ │ ├── PlayerWindow.xaml(.cs) # Bağımsız PiP destekli oynatıcı penceresi
│ │ └── ChatWindow.xaml(.cs) # Bağımsız canlı sohbet penceresi
│ └── Resources/
│ ├── Styles.xaml # Özel koyu tema ve modern WPF kontrol şablonları
│ └── app.ico # Çoklu çözünürlüklü LD KickWatch simgesi
└── LICENSE
```
---
## 📄 Lisans
Bu proje [MIT Lisansı](./LICENSE) altında lisanslanmıştır.

BIN
publish/LDKickWatch.exe Normal file

Binary file not shown.

View file

@ -0,0 +1,33 @@
<Application x:Class="KickStreamHub.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:conv="clr-namespace:KickStreamHub.Converters">
<Application.Resources>
<ResourceDictionary>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<conv:BoolToVisibilityInverseConverter x:Key="InverseBoolToVis" />
<conv:LiveToBrushConverter x:Key="LiveToBrush" />
<conv:LiveTextConverter x:Key="LiveTextConverter" />
<conv:ChatConnectionTextConverter x:Key="ChatConnTextConverter" />
<conv:PauseTextConverter x:Key="PauseTextConverter" />
<conv:ViewerFormatConverter x:Key="ViewerFormat" />
<conv:StringToBrushConverter x:Key="StringToBrush" />
<conv:PageVisibilityConverter x:Key="PageVisConverter" />
<conv:ActivePageMatchConverter x:Key="ActivePageMatch" />
<conv:NonEmptyToVisibilityConverter x:Key="NonEmptyToVis" />
<conv:NullToVisibilityConverter x:Key="NullToVis" />
<conv:PlayButtonTextConverter x:Key="PlayButtonTextConverter" />
<conv:TheaterButtonTextConverter x:Key="TheaterButtonTextConverter" />
<conv:FullScreenButtonTextConverter x:Key="FullScreenButtonTextConverter" />
<conv:MuteButtonTextConverter x:Key="MuteButtonTextConverter" />
<conv:MultiLayoutTextConverter x:Key="MultiLayoutTextConverter" />
<conv:SoloAudioTextConverter x:Key="SoloAudioTextConverter" />
<conv:InitialsConverter x:Key="InitialsConverter" />
<conv:AvatarImageConverter x:Key="AvatarImageConverter" />
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

View file

@ -0,0 +1,98 @@
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using KickStreamHub.Services;
using KickStreamHub.Views;
namespace KickStreamHub;
public partial class App : System.Windows.Application
{
private const string MutexName = @"Local\LDKickWatch_SingleInstance_Mutex";
private const string ActivateEventName = @"Local\LDKickWatch_Activate_Event";
private static Mutex? _singleInstanceMutex;
private static EventWaitHandle? _activateEvent;
private static bool _ownsMutex;
private MainWindow? _mainWindow;
protected override void OnStartup(StartupEventArgs e)
{
_singleInstanceMutex = new Mutex(true, MutexName, out bool isNewInstance);
_ownsMutex = isNewInstance;
if (!isNewInstance)
{
// Çalışmakta olan örneği öne getir
try
{
using var evt = EventWaitHandle.OpenExisting(ActivateEventName);
evt.Set();
}
catch { }
System.Windows.MessageBox.Show(
"LD KickWatch zaten çalışıyor! Açık olan pencere ekrana getirildi.",
"LD KickWatch",
MessageBoxButton.OK,
MessageBoxImage.Information);
Environment.Exit(0);
return;
}
ShutdownMode = ShutdownMode.OnMainWindowClose;
// İkinci bir örnek açılmaya çalışıldığında ana pencereyi öne getiren dinleyici
_activateEvent = new EventWaitHandle(false, EventResetMode.AutoReset, ActivateEventName);
ThreadPool.RegisterWaitForSingleObject(_activateEvent, (_, _) =>
{
Dispatcher.BeginInvoke(() =>
{
if (_mainWindow != null)
{
_mainWindow.RestoreAndBringToFront();
}
});
}, null, -1, false);
base.OnStartup(e);
DispatcherUnhandledException += OnDispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
_mainWindow = new MainWindow();
MainWindow = _mainWindow;
_mainWindow.Show();
}
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
LoggingService.Instance.Error("Yakalanmayan UI hatası", e.Exception);
e.Handled = true;
}
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is Exception ex)
LoggingService.Instance.Error("Yakalanmayan genel hata", ex);
}
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
LoggingService.Instance.Error("Gözlemlenmeyen görev (task) hatası", e.Exception);
e.SetObserved();
}
protected override void OnExit(ExitEventArgs e)
{
try { _activateEvent?.Dispose(); } catch { }
if (_ownsMutex)
{
try { _singleInstanceMutex?.ReleaseMutex(); } catch { }
}
try { _singleInstanceMutex?.Dispose(); } catch { }
base.OnExit(e);
}
}

View file

@ -0,0 +1,257 @@
using System.Collections.Concurrent;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using WpfColor = System.Windows.Media.Color;
using WpfColors = System.Windows.Media.Colors;
using WpfColorConverter = System.Windows.Media.ColorConverter;
namespace KickStreamHub.Converters;
public class BoolToVisibilityInverseConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? Visibility.Collapsed : Visibility.Visible;
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class LiveTextConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? "● CANLI YAYINDA" : "ÇEVRİMDIŞI";
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class ChatConnectionTextConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? "Bağlı" : "Bağlanıyor...";
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class LiveToBrushConverter : IValueConverter
{
private static readonly SolidColorBrush LiveBrush = new(WpfColor.FromRgb(0, 231, 1));
private static readonly SolidColorBrush OfflineBrush = new(WpfColor.FromRgb(51, 65, 85));
static LiveToBrushConverter() { LiveBrush.Freeze(); OfflineBrush.Freeze(); }
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
var isLive = value is true;
if (targetType == typeof(WpfColor))
return isLive ? WpfColors.LimeGreen : WpfColors.SlateGray;
return isLive ? LiveBrush : OfflineBrush;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class PauseTextConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? "▶ Devam" : "⏸ Duraklat";
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class ViewerFormatConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is long v)
return v >= 1000 ? $"{v / 1000.0:0.0}B" : v.ToString();
return "0";
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class PageVisibilityConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is string current && parameter is string target)
return current.Equals(target, StringComparison.OrdinalIgnoreCase)
? Visibility.Visible : Visibility.Collapsed;
return Visibility.Collapsed;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class ActivePageMatchConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is string current && parameter is string target)
return current.Equals(target, StringComparison.OrdinalIgnoreCase);
return false;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class NonEmptyToVisibilityConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
bool hasText = value is string s && !string.IsNullOrWhiteSpace(s);
bool invert = parameter is string p && p.Equals("invert", StringComparison.OrdinalIgnoreCase);
if (invert) hasText = !hasText;
return hasText ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class NullToVisibilityConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
bool isNotNull = value is not null;
bool invert = parameter is string p && p.Equals("invert", StringComparison.OrdinalIgnoreCase);
if (invert) isNotNull = !isNotNull;
return isNotNull ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class PlayButtonTextConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? "⏹ YAYINI DURDUR" : "▶ YAYINI İZLE";
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class TheaterButtonTextConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? "🗗 Normal" : "🗖 Sinema Modu";
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class FullScreenButtonTextConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? "🗗 Çık (Esc)" : "⛶ Tam Ekran";
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class MuteButtonTextConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? "🔇 Sesi Aç" : "🔊 Sesi Kapat";
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class MultiLayoutTextConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? "▯▯ 2'li Yan Yana Mod" : "⊞ 4'lü (2x2) Izgara Mod";
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class SoloAudioTextConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? "🔇 Bu Ekranı Dinle" : "🔊 Ses Açık";
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class InitialsConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is string s && !string.IsNullOrWhiteSpace(s))
{
var clean = s.Trim().TrimStart('@');
if (clean.Length == 0) return "?";
return clean.Length >= 2 ? clean[..2].ToUpperInvariant() : clean[..1].ToUpperInvariant();
}
return "?";
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
/// <summary>
/// Diskteki avatar dosyasını kilitlemeden (BitmapCacheOption.OnLoad) belleğe yükler.
/// Böylece AvatarCacheService dosyayı güncellerken IOException (file lock) oluşmaz.
/// </summary>
public class AvatarImageConverter : IValueConverter
{
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is not string path || string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return null;
try
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
bitmap.DecodePixelWidth = 140;
bitmap.StreamSource = stream;
bitmap.EndInit();
bitmap.Freeze();
return bitmap;
}
catch
{
return null;
}
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
public class StringToBrushConverter : IValueConverter
{
private static readonly ConcurrentDictionary<string, SolidColorBrush> BrushCache = new(StringComparer.OrdinalIgnoreCase);
private static readonly SolidColorBrush DefaultBrush = CreateFrozenBrush(WpfColor.FromRgb(0, 231, 1));
private static SolidColorBrush CreateFrozenBrush(WpfColor color)
{
var brush = new SolidColorBrush(color);
brush.Freeze();
return brush;
}
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is string hex && !string.IsNullOrWhiteSpace(hex))
{
return BrushCache.GetOrAdd(hex.Trim(), key =>
{
try
{
var color = (WpfColor)WpfColorConverter.ConvertFromString(key);
return CreateFrozenBrush(color);
}
catch
{
return DefaultBrush;
}
});
}
return DefaultBrush;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
throw new NotSupportedException();
}

View file

@ -0,0 +1,169 @@
using System.Collections.Concurrent;
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using KickStreamHub.Converters;
using KickStreamHub.ViewModels;
using WpfColor = System.Windows.Media.Color;
using WpfImage = System.Windows.Controls.Image;
namespace KickStreamHub.Helpers;
/// <summary>
/// Kick sohbet mesajlarındaki [emote:ID:Name] ifadelerini gerçek görsel (InlineUIContainer + Image)
/// olarak ayrıştırır ve bellek içi önbellek (EmoteCache) ile yüksek performanslı şekilde TextBlock'a çizer.
/// </summary>
public static partial class RichChatHelper
{
[GeneratedRegex(@"\[emote:(\d+):([^\]]+)\]")]
private static partial Regex EmotePattern();
private static readonly ConcurrentDictionary<string, BitmapImage> EmoteCache = new(StringComparer.OrdinalIgnoreCase);
private static readonly StringToBrushConverter BrushConverter = new();
private static readonly SolidColorBrush TimeBrush = CreateFrozenBrush(WpfColor.FromRgb(71, 85, 105));
private static readonly SolidColorBrush MessageBrush = CreateFrozenBrush(WpfColor.FromRgb(226, 232, 240));
private static readonly SolidColorBrush EmoteFallbackBrush = CreateFrozenBrush(WpfColor.FromRgb(83, 252, 24));
private static readonly HttpClient EmoteHttp = CreateEmoteClient();
private static HttpClient CreateEmoteClient()
{
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(8) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0");
return client;
}
private static SolidColorBrush CreateFrozenBrush(WpfColor color)
{
var b = new SolidColorBrush(color);
b.Freeze();
return b;
}
public static readonly DependencyProperty MessageItemProperty =
DependencyProperty.RegisterAttached(
"MessageItem",
typeof(ChatMessageItem),
typeof(RichChatHelper),
new PropertyMetadata(null, OnMessageItemChanged));
public static void SetMessageItem(DependencyObject element, ChatMessageItem? value) =>
element.SetValue(MessageItemProperty, value);
public static ChatMessageItem? GetMessageItem(DependencyObject element) =>
(ChatMessageItem?)element.GetValue(MessageItemProperty);
private static void OnMessageItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not TextBlock tb) return;
tb.Inlines.Clear();
if (e.NewValue is not ChatMessageItem item) return;
// 1. Zaman damgası
tb.Inlines.Add(new Run($"{item.TimeFormatted} ")
{
Foreground = TimeBrush,
FontSize = 10,
});
// 2. Kullanıcı adı
var userBrush = BrushConverter.Convert(item.ColorHex, typeof(System.Windows.Media.Brush), null, System.Globalization.CultureInfo.InvariantCulture) as System.Windows.Media.Brush ?? EmoteFallbackBrush;
tb.Inlines.Add(new Run($"{item.Username}: ")
{
FontWeight = FontWeights.Bold,
Foreground = userBrush,
});
// 3. Mesaj içeriği ve Kick Emote görselleri
var raw = string.IsNullOrEmpty(item.RawMessage) ? item.Message : item.RawMessage;
var matches = EmotePattern().Matches(raw);
if (matches.Count == 0)
{
tb.Inlines.Add(new Run(raw) { Foreground = MessageBrush });
return;
}
int lastIndex = 0;
foreach (Match match in matches)
{
if (match.Index > lastIndex)
{
var textSegment = raw[lastIndex..match.Index];
tb.Inlines.Add(new Run(textSegment) { Foreground = MessageBrush });
}
var emoteId = match.Groups[1].Value;
var emoteName = match.Groups[2].Value;
var img = new WpfImage
{
Width = 22,
Height = 22,
Margin = new Thickness(2, 0, 2, -4),
Stretch = Stretch.Uniform,
ToolTip = $":{emoteName}:",
};
RenderOptions.SetBitmapScalingMode(img, BitmapScalingMode.HighQuality);
var container = new InlineUIContainer(img)
{
BaselineAlignment = BaselineAlignment.Center
};
tb.Inlines.Add(container);
if (EmoteCache.TryGetValue(emoteId, out var cachedBmp))
{
img.Source = cachedBmp;
}
else
{
_ = LoadEmoteImageAsync(emoteId, img);
}
lastIndex = match.Index + match.Length;
}
if (lastIndex < raw.Length)
{
tb.Inlines.Add(new Run(raw[lastIndex..]) { Foreground = MessageBrush });
}
}
private static async Task LoadEmoteImageAsync(string emoteId, WpfImage targetImage)
{
try
{
var url = $"https://files.kick.com/emotes/{emoteId}/fullsize";
var bytes = await EmoteHttp.GetByteArrayAsync(url).ConfigureAwait(false);
if (bytes.Length == 0) return;
var bmp = new BitmapImage();
using (var ms = new MemoryStream(bytes))
{
bmp.BeginInit();
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.DecodePixelHeight = 44;
bmp.StreamSource = ms;
bmp.EndInit();
}
bmp.Freeze();
EmoteCache[emoteId] = bmp;
await targetImage.Dispatcher.InvokeAsync(() =>
{
targetImage.Source = bmp;
});
}
catch
{
// İndirilemezse sessizce geç
}
}
}

View file

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>KickStreamHub</RootNamespace>
<AssemblyName>LDKickWatch</AssemblyName>
<Version>1.2.0</Version>
<Product>LD KickWatch</Product>
<AssemblyTitle>LD KickWatch</AssemblyTitle>
<Company>LD KickWatch</Company>
<ApplicationIcon>Resources\app.ico</ApplicationIcon>
<LangVersion>latest</LangVersion>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
<Platforms>AnyCPU</Platforms>
</PropertyGroup>
<ItemGroup>
<Resource Include="Resources\app.ico" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4314.35" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,39 @@
using System.Collections.ObjectModel;
namespace KickStreamHub.Models;
public class AppConfig
{
public ObservableCollection<string> Favorites { get; set; } = new()
{
"elwind", "wtcn", "pqueen", "unlostv", "kendinemuzisyen"
};
public Dictionary<string, string> ChannelGroups { get; set; } = new(StringComparer.OrdinalIgnoreCase);
public string PlayerChoice { get; set; } = "embedded";
public int RefreshIntervalSeconds { get; set; } = 90;
public bool StartMinimized { get; set; } = false;
public bool MinimizeToTray { get; set; } = false;
public bool NotificationsEnabled { get; set; } = true;
public bool SoundNotificationsEnabled { get; set; } = true;
public string CustomSoundPath { get; set; } = string.Empty;
public bool NotifyOnCategoryChange { get; set; } = true;
public string AlertKeywords { get; set; } = string.Empty;
public bool RunOnStartup { get; set; } = false;
public bool AutoOpenChat { get; set; } = false;
public bool ShowEmbeddedChat { get; set; } = true;
public double WindowWidth { get; set; } = 1320;
public double WindowHeight { get; set; } = 800;
public double WindowLeft { get; set; } = -1;
public double WindowTop { get; set; } = -1;
public string StreamlinkPath { get; set; } = string.Empty;
public string PlayerPath { get; set; } = string.Empty;
public string StreamQuality { get; set; } = "best";
public string ExtraStreamlinkArgs { get; set; } = string.Empty;
public string ActivePage { get; set; } = "home";
public int ChatMaxMessages { get; set; } = 500;
}

View file

@ -0,0 +1,16 @@
namespace KickStreamHub.Models;
public class ChannelStatus
{
public string ChannelName { get; set; } = string.Empty;
public bool IsLive { get; set; }
public string Title { get; set; } = string.Empty;
public string Category { get; set; } = string.Empty;
public long Viewers { get; set; }
public bool Verified { get; set; }
public string ProfilePicUrl { get; set; } = string.Empty;
public string PlaybackUrl { get; set; } = string.Empty;
public long? ChatroomId { get; set; }
public bool FetchSucceeded { get; set; } = true;
public DateTime FetchedAt { get; set; } = DateTime.Now;
}

View file

@ -0,0 +1,60 @@
using System.Text.Json.Serialization;
namespace KickStreamHub.Models;
public class KickChannelResponse
{
[JsonPropertyName("id")]
public long Id { get; set; }
[JsonPropertyName("slug")]
public string? Slug { get; set; }
[JsonPropertyName("verified")]
public bool Verified { get; set; }
[JsonPropertyName("playback_url")]
public string? PlaybackUrl { get; set; }
[JsonPropertyName("user")]
public KickUser? User { get; set; }
[JsonPropertyName("livestream")]
public KickLivestream? Livestream { get; set; }
[JsonPropertyName("chatroom")]
public KickChatroom? Chatroom { get; set; }
}
public class KickUser
{
[JsonPropertyName("username")]
public string? Username { get; set; }
[JsonPropertyName("profile_pic")]
public string? ProfilePic { get; set; }
}
public class KickLivestream
{
[JsonPropertyName("session_title")]
public string? SessionTitle { get; set; }
[JsonPropertyName("viewer_count")]
public long ViewerCount { get; set; }
[JsonPropertyName("categories")]
public List<KickCategory>? Categories { get; set; }
}
public class KickCategory
{
[JsonPropertyName("name")]
public string? Name { get; set; }
}
public class KickChatroom
{
[JsonPropertyName("id")]
public long Id { get; set; }
}

View file

@ -0,0 +1,384 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- Color Palette -->
<SolidColorBrush x:Key="BgBrush" Color="#060A10" />
<SolidColorBrush x:Key="PanelBrush" Color="#0B111A" />
<SolidColorBrush x:Key="CardBrush" Color="#111926" />
<SolidColorBrush x:Key="CardHoverBrush" Color="#172234" />
<SolidColorBrush x:Key="BorderBrush" Color="#1E2B3E" />
<SolidColorBrush x:Key="TextBrush" Color="#F1F5F9" />
<SolidColorBrush x:Key="SubtleTextBrush" Color="#94A3B8" />
<SolidColorBrush x:Key="MutedTextBrush" Color="#64748B" />
<SolidColorBrush x:Key="AccentBrush" Color="#53FC18" />
<SolidColorBrush x:Key="AccentDarkBrush" Color="#00C801" />
<SolidColorBrush x:Key="DangerBrush" Color="#EF4444" />
<!-- Default Window Style -->
<Style TargetType="Window">
<Setter Property="Background" Value="{StaticResource BgBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="TextOptions.TextFormattingMode" Value="Ideal" />
</Style>
<!-- Primary Accent Button -->
<Style TargetType="Button" x:Key="PrimaryButton">
<Setter Property="Background" Value="{StaticResource AccentBrush}" />
<Setter Property="Foreground" Value="#041208" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Padding" Value="12,7" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="border" Background="{TemplateBinding Background}" CornerRadius="8" Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="#6DFF3B" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Background" Value="#3CD00B" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="border" Property="Opacity" Value="0.45" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Secondary Dark Button -->
<Style TargetType="Button" x:Key="SecondaryButton">
<Setter Property="Background" Value="#141E2E" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Padding" Value="11,7" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="8" Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="#1E2C42" />
<Setter TargetName="border" Property="BorderBrush" Value="#314666" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Background" Value="#0E1520" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="border" Property="Opacity" Value="0.45" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Subtle Danger Button (for delete/close) -->
<Style TargetType="Button" x:Key="DangerButton">
<Setter Property="Background" Value="#181824" />
<Setter Property="Foreground" Value="#94A3B8" />
<Setter Property="Padding" Value="8,5" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="#252A3A" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="7" Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="#35161E" />
<Setter TargetName="border" Property="BorderBrush" Value="#EF4444" />
<Setter Property="Foreground" Value="#FCA5A5" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Background" Value="#4C1519" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Filter Toggle Button (All / Live Only) -->
<Style TargetType="ToggleButton" x:Key="FilterChipToggle">
<Setter Property="Background" Value="#101824" />
<Setter Property="Foreground" Value="#94A3B8" />
<Setter Property="BorderBrush" Value="#1E2B3E" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="10,5" />
<Setter Property="FontSize" Value="11" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="7" Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="#192538" />
<Setter Property="Foreground" Value="#E2E8F0" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="border" Property="Background" Value="#132D19" />
<Setter TargetName="border" Property="BorderBrush" Value="#53FC18" />
<Setter Property="Foreground" Value="#53FC18" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Modern TextBox with Tag Placeholder Watermark -->
<Style TargetType="TextBox">
<Setter Property="Background" Value="#0D141F" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="10,7" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="CaretBrush" Value="{StaticResource AccentBrush}" />
<Setter Property="SelectionBrush" Value="#2D6A1E" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Border x:Name="border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="8">
<Grid>
<ScrollViewer x:Name="PART_ContentHost"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Focusable="False"
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden" />
<TextBlock x:Name="Placeholder"
Text="{TemplateBinding Tag}"
Foreground="#56677D"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
IsHitTestVisible="False"
Visibility="Collapsed" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="Text" Value="">
<Setter TargetName="Placeholder" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter TargetName="Placeholder" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="#2D415E" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
<Setter TargetName="border" Property="Background" Value="#101927" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Modern Dark ComboBoxItem -->
<Style TargetType="ComboBoxItem">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="Padding" Value="10,8" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBoxItem">
<Border x:Name="bd" Background="{TemplateBinding Background}" CornerRadius="6" Margin="3,1" Padding="{TemplateBinding Padding}">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="bd" Property="Background" Value="#1D2B40" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bd" Property="Background" Value="#16331D" />
<Setter Property="Foreground" Value="{StaticResource AccentBrush}" />
<Setter Property="FontWeight" Value="SemiBold" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Modern Dark ComboBox -->
<Style TargetType="ComboBox">
<Setter Property="Background" Value="#0D141F" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="10,7" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox">
<Grid>
<ToggleButton x:Name="ToggleButton"
Focusable="False"
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
ClickMode="Press">
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<Border x:Name="border"
Background="#0D141F"
BorderBrush="{StaticResource BorderBrush}"
BorderThickness="1"
CornerRadius="8">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="32" />
</Grid.ColumnDefinitions>
<Path Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Data="M 0 0 L 5 5 L 10 0"
Stroke="#94A3B8"
StrokeThickness="1.6" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="#2D415E" />
<Setter TargetName="border" Property="Background" Value="#121C2B" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<ContentPresenter x:Name="ContentSite"
IsHitTestVisible="False"
Content="{TemplateBinding SelectionBoxItem}"
ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
Margin="12,7,32,7"
VerticalAlignment="Center"
HorizontalAlignment="Left" />
<Popup x:Name="Popup"
Placement="Bottom"
IsOpen="{TemplateBinding IsDropDownOpen}"
AllowsTransparency="True"
Focusable="False"
PopupAnimation="Fade">
<Grid x:Name="DropDown"
SnapsToDevicePixels="True"
MinWidth="{TemplateBinding ActualWidth}"
MaxHeight="{TemplateBinding MaxDropDownHeight}"
Margin="0,4,0,0">
<Border x:Name="DropDownBorder"
Background="#111A28"
BorderBrush="#293B54"
BorderThickness="1"
CornerRadius="8"
Padding="2,4">
<ScrollViewer SnapsToDevicePixels="True">
<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
</ScrollViewer>
</Border>
</Grid>
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Modern CheckBox -->
<Style TargetType="CheckBox">
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="CheckBox">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" Background="Transparent">
<Border x:Name="checkBoxBorder"
Width="19" Height="19"
CornerRadius="5"
Background="#0D141F"
BorderBrush="#2A3B52"
BorderThickness="1.5"
VerticalAlignment="Center">
<Path x:Name="checkMark"
Data="M 3.5 9.5 L 7.5 13.5 L 15.5 5"
Stroke="#041208"
StrokeThickness="2.2"
Visibility="Collapsed" />
</Border>
<ContentPresenter Margin="9,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="checkBoxBorder" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="checkBoxBorder" Property="Background" Value="{StaticResource AccentBrush}" />
<Setter TargetName="checkBoxBorder" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
<Setter TargetName="checkMark" Property="Visibility" Value="Visible" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Modern Thin ScrollBar -->
<Style TargetType="ScrollBar">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Width" Value="6" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ScrollBar">
<Grid Background="Transparent" Width="{TemplateBinding Width}">
<Track x:Name="PART_Track" IsDirectionReversed="True">
<Track.Thumb>
<Thumb>
<Thumb.Template>
<ControlTemplate TargetType="Thumb">
<Border Background="#26364D" CornerRadius="3" />
</ControlTemplate>
</Thumb.Template>
</Thumb>
</Track.Thumb>
</Track>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View file

@ -0,0 +1,81 @@
using System.IO;
namespace KickStreamHub.Services;
/// <summary>
/// Kanal avatarlarını diskte önbelleğe alır (TTL: 24 saat) ve gerektiğinde
/// KickApiService üzerinden indirir. Tüm dosya G/Ç işlemleri iş parçacığı
/// güvenlidir; her indirme kendi dosya adını kullandığından çakışma olmaz.
/// </summary>
public sealed class AvatarCacheService
{
private static readonly TimeSpan Ttl = TimeSpan.FromHours(24);
private readonly string _cacheDir;
private readonly KickApiService _api;
public AvatarCacheService(string cacheDir, KickApiService api)
{
_cacheDir = cacheDir;
_api = api;
}
public string GetCachePath(string channelName) => Path.Combine(_cacheDir, $"{Sanitize(channelName)}.png");
private static string Sanitize(string name)
{
foreach (var c in Path.GetInvalidFileNameChars())
name = name.Replace(c, '_');
return name;
}
public bool TryGetFreshCachedPath(string channelName, out string path)
{
path = GetCachePath(channelName);
if (!File.Exists(path)) return false;
var age = DateTime.UtcNow - File.GetLastWriteTimeUtc(path);
return age < Ttl;
}
public async Task<string?> DownloadAndCacheAsync(string channelName, string url, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(url)) return null;
var bytes = await _api.GetImageBytesAsync(url, ct).ConfigureAwait(false);
if (bytes is null || bytes.Length == 0) return null;
var path = GetCachePath(channelName);
try
{
var tmp = path + ".tmp";
await File.WriteAllBytesAsync(tmp, bytes, ct).ConfigureAwait(false);
File.Move(tmp, path, overwrite: true);
return path;
}
catch (Exception ex)
{
LoggingService.Instance.Warning($"Avatar önbelleğe yazılamadı ({channelName}): {ex.Message}");
return null;
}
}
public void CleanupStale(IEnumerable<string> activeChannels)
{
try
{
var activeSet = new HashSet<string>(activeChannels.Select(Sanitize), StringComparer.OrdinalIgnoreCase);
foreach (var file in Directory.EnumerateFiles(_cacheDir, "*.png"))
{
var name = Path.GetFileNameWithoutExtension(file);
var age = DateTime.UtcNow - File.GetLastWriteTimeUtc(file);
if (!activeSet.Contains(name) && age > TimeSpan.FromDays(7))
{
File.Delete(file);
}
}
}
catch (Exception ex)
{
LoggingService.Instance.Warning($"Avatar önbellek temizliği başarısız: {ex.Message}");
}
}
}

View file

@ -0,0 +1,75 @@
using System.IO;
using System.Text.Json;
using KickStreamHub.Models;
namespace KickStreamHub.Services;
/// <summary>
/// Uygulama yapılandırmasını %LOCALAPPDATA%\LDKickWatch\config.json
/// dosyasında saklar. Eski KickStreamHub klasöründe yapılandırma varsa ilk
/// açılışta otomatik olarak taşır.
/// </summary>
public sealed class ConfigService
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
};
public string AppDataDirectory { get; }
public string ConfigFilePath { get; }
public string AvatarCacheDirectory { get; }
public ConfigService()
{
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
AppDataDirectory = Path.Combine(localAppData, "LDKickWatch");
Directory.CreateDirectory(AppDataDirectory);
AvatarCacheDirectory = Path.Combine(AppDataDirectory, "avatars");
Directory.CreateDirectory(AvatarCacheDirectory);
ConfigFilePath = Path.Combine(AppDataDirectory, "config.json");
// Eski klasörden (KickStreamHub) ayarları otomatik taşı
if (!File.Exists(ConfigFilePath))
{
var legacyConfig = Path.Combine(localAppData, "KickStreamHub", "config.json");
if (File.Exists(legacyConfig))
{
try { File.Copy(legacyConfig, ConfigFilePath, overwrite: false); } catch { }
}
}
}
public AppConfig Load()
{
try
{
if (!File.Exists(ConfigFilePath))
return new AppConfig();
var json = File.ReadAllText(ConfigFilePath);
var config = JsonSerializer.Deserialize<AppConfig>(json);
return config ?? new AppConfig();
}
catch (Exception ex)
{
LoggingService.Instance.Error("Yapılandırma okunamadı, varsayılana dönülüyor.", ex);
return new AppConfig();
}
}
public void Save(AppConfig config)
{
try
{
var json = JsonSerializer.Serialize(config, JsonOptions);
File.WriteAllText(ConfigFilePath, json);
}
catch (Exception ex)
{
LoggingService.Instance.Error("Yapılandırma kaydedilemedi.", ex);
}
}
}

View file

@ -0,0 +1,79 @@
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using KickStreamHub.Models;
namespace KickStreamHub.Services;
/// <summary>
/// Kick.com genel API'siyle konuşan servis. .NET'in HttpClient'ı, Python
/// tarafında yaşanan curl_cffi kütüphanesinin aksine, birden fazla iş
/// parçacığından EŞZAMANLI olarak güvenle kullanılabilir; bu, eski Python
/// sürümünde uygulamanın rastgele çökmesine (access violation) yol açan
/// kök nedeni tamamen ortadan kaldırır.
/// </summary>
public sealed class KickApiService
{
private const string ApiBaseV2 = "https://kick.com/api/v2/channels";
private const string ApiBaseV1 = "https://kick.com/api/v1/channels";
private static readonly HttpClient Http = CreateClient();
private static HttpClient CreateClient()
{
var handler = new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
AutomaticDecompression = System.Net.DecompressionMethods.All,
UseProxy = false,
};
var client = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(12),
};
client.DefaultRequestHeaders.UserAgent.ParseAdd(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.9");
return client;
}
public async Task<KickChannelResponse?> GetChannelAsync(string channelName, CancellationToken ct = default)
{
foreach (var baseUrl in new[] { ApiBaseV2, ApiBaseV1 })
{
try
{
using var resp = await Http.GetAsync($"{baseUrl}/{channelName}", ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode)
continue;
var stream = await resp.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
var data = await JsonSerializer.DeserializeAsync<KickChannelResponse>(stream, cancellationToken: ct)
.ConfigureAwait(false);
if (data != null)
return data;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LoggingService.Instance.Warning($"Kanal bilgisi alınamadı ({channelName}, {baseUrl}): {ex.Message}");
}
}
return null;
}
public async Task<byte[]?> GetImageBytesAsync(string url, CancellationToken ct = default)
{
try
{
using var resp = await Http.GetAsync(url, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return null;
return await resp.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LoggingService.Instance.Warning($"Görsel indirilemedi ({url}): {ex.Message}");
return null;
}
}
}

View file

@ -0,0 +1,127 @@
using System.Collections.Concurrent;
using KickStreamHub.Models;
namespace KickStreamHub.Services;
public class LiveStatusResultEventArgs : EventArgs
{
public IReadOnlyDictionary<string, ChannelStatus> Results { get; }
public LiveStatusResultEventArgs(IReadOnlyDictionary<string, ChannelStatus> results) => Results = results;
}
/// <summary>
/// Favori kanalların canlı yayın durumunu belirli aralıklarla, sınırlı
/// eşzamanlılıkla (SemaphoreSlim) sorgular. .NET HttpClient thread-safe
/// olduğu için burada onlarca kanal aynı anda güvenle sorgulanabilir.
/// </summary>
public sealed class LiveStatusPollingService : IDisposable
{
private readonly KickApiService _api;
private readonly SemaphoreSlim _concurrencyLimiter = new(6);
private System.Threading.Timer? _timer;
private int _isPolling;
private IReadOnlyList<string> _channels = Array.Empty<string>();
public event EventHandler<LiveStatusResultEventArgs>? ResultsReady;
public event EventHandler<string>? StatusMessage;
public LiveStatusPollingService(KickApiService api)
{
_api = api;
}
public void UpdateChannelList(IReadOnlyList<string> channels) => _channels = channels;
public void Start(int intervalSeconds)
{
Stop();
_timer = new System.Threading.Timer(async _ => await PollOnceSafeAsync().ConfigureAwait(false),
null, TimeSpan.Zero, TimeSpan.FromSeconds(intervalSeconds));
}
public void Stop()
{
_timer?.Dispose();
_timer = null;
}
public Task RefreshNowAsync() => PollOnceSafeAsync(isManual: true);
private async Task PollOnceSafeAsync(bool isManual = false)
{
if (Interlocked.CompareExchange(ref _isPolling, 1, 0) != 0) return;
try
{
await PollOnceAsync(isManual).ConfigureAwait(false);
}
catch (Exception ex)
{
LoggingService.Instance.Error("Canlı yayın kontrolü sırasında hata", ex);
}
finally
{
Interlocked.Exchange(ref _isPolling, 0);
}
}
private async Task PollOnceAsync(bool isManual = false)
{
var channels = _channels;
if (channels.Count == 0) return;
if (isManual)
{
StatusMessage?.Invoke(this, $"{channels.Count} kanal sorgulanıyor...");
}
var results = new ConcurrentDictionary<string, ChannelStatus>();
var tasks = channels.Select(async channel =>
{
await _concurrencyLimiter.WaitAsync().ConfigureAwait(false);
try
{
var status = await FetchOneAsync(channel).ConfigureAwait(false);
results[channel] = status;
}
finally
{
_concurrencyLimiter.Release();
}
});
await Task.WhenAll(tasks).ConfigureAwait(false);
ResultsReady?.Invoke(this, new LiveStatusResultEventArgs(results));
StatusMessage?.Invoke(this, $"✔ {channels.Count} kanal güncellendi.");
}
private async Task<ChannelStatus> FetchOneAsync(string channel)
{
var data = await _api.GetChannelAsync(channel).ConfigureAwait(false);
if (data is null)
{
return new ChannelStatus { ChannelName = channel, FetchSucceeded = false };
}
var live = data.Livestream;
return new ChannelStatus
{
ChannelName = channel,
IsLive = live is not null,
Title = live?.SessionTitle ?? string.Empty,
Category = live?.Categories?.FirstOrDefault()?.Name ?? string.Empty,
Viewers = live?.ViewerCount ?? 0,
Verified = data.Verified,
ProfilePicUrl = data.User?.ProfilePic ?? string.Empty,
PlaybackUrl = data.PlaybackUrl ?? string.Empty,
ChatroomId = data.Chatroom?.Id,
FetchSucceeded = true,
};
}
public void Dispose()
{
Stop();
_concurrencyLimiter.Dispose();
}
}

View file

@ -0,0 +1,71 @@
using System.IO;
using System.Text;
namespace KickStreamHub.Services;
public enum LogLevel { Info, Warning, Error }
/// <summary>
/// Basit, dosya tabanlı, iş parçacığı güvenli (thread-safe) log servisi.
/// %LOCALAPPDATA%\KickStreamHub\logs\app.log dosyasına yazar ve
/// belirli bir boyutu (5 MB) aştığında dosyayı döndürür (rotate).
/// </summary>
public sealed class LoggingService
{
private static readonly Lazy<LoggingService> _instance = new(() => new LoggingService());
public static LoggingService Instance => _instance.Value;
private readonly string _logFilePath;
private readonly object _lock = new();
private const long MaxSizeBytes = 5 * 1024 * 1024;
private LoggingService()
{
var dir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"LDKickWatch", "logs");
Directory.CreateDirectory(dir);
_logFilePath = Path.Combine(dir, "app.log");
}
public void Info(string message) => Write(LogLevel.Info, message);
public void Warning(string message) => Write(LogLevel.Warning, message);
public void Error(string message, Exception? ex = null) =>
Write(LogLevel.Error, ex is null ? message : $"{message} :: {ex}");
private void Write(LogLevel level, string message)
{
var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}";
lock (_lock)
{
try
{
RotateIfNeeded();
File.AppendAllText(_logFilePath, line + Environment.NewLine, Encoding.UTF8);
}
catch
{
// Loglama asla uygulamayı çökertmemeli.
}
}
}
private void RotateIfNeeded()
{
if (!File.Exists(_logFilePath)) return;
var info = new FileInfo(_logFilePath);
if (info.Length < MaxSizeBytes) return;
var backup = Path.ChangeExtension(_logFilePath, ".1.log");
try
{
if (File.Exists(backup)) File.Delete(backup);
File.Move(_logFilePath, backup);
}
catch
{
// yoksay
}
}
public string LogDirectory => Path.GetDirectoryName(_logFilePath)!;
}

View file

@ -0,0 +1,71 @@
using System.Windows.Forms;
using Application = System.Windows.Application;
namespace KickStreamHub.Services;
/// <summary>
/// Sistem tepsisi simgesini ve bildirimleri (balloon tip) yönetir.
/// </summary>
public sealed class NotificationService : IDisposable
{
private readonly NotifyIcon _notifyIcon;
public event EventHandler? OpenRequested;
public event EventHandler? ExitRequested;
public NotificationService()
{
System.Drawing.Icon? customIcon = null;
try
{
var streamInfo = Application.GetResourceStream(new Uri("pack://application:,,,/Resources/app.ico"));
if (streamInfo?.Stream != null)
{
customIcon = new System.Drawing.Icon(streamInfo.Stream);
}
}
catch { }
_notifyIcon = new NotifyIcon
{
Icon = customIcon ?? System.Drawing.SystemIcons.Application,
Text = "LD KickWatch",
Visible = false,
};
var menu = new ContextMenuStrip();
menu.Items.Add("LD KickWatch'u Göster", null, (_, _) => OpenRequested?.Invoke(this, EventArgs.Empty));
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add("Çıkış", null, (_, _) => ExitRequested?.Invoke(this, EventArgs.Empty));
_notifyIcon.ContextMenuStrip = menu;
_notifyIcon.DoubleClick += (_, _) => OpenRequested?.Invoke(this, EventArgs.Empty);
}
public void Show() => _notifyIcon.Visible = true;
public void Hide() => _notifyIcon.Visible = false;
public void ShowBalloon(string title, string text)
{
try
{
_notifyIcon.BalloonTipTitle = title;
_notifyIcon.BalloonTipText = text;
_notifyIcon.ShowBalloonTip(6000);
}
catch
{
// bildirim gösterilemezse sessizce yoksay
}
}
public void Dispose()
{
try
{
_notifyIcon.Visible = false;
_notifyIcon.Dispose();
}
catch { }
}
}

View file

@ -0,0 +1,262 @@
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace KickStreamHub.Services;
public class ChatMessageEventArgs : EventArgs
{
public string Username { get; init; } = string.Empty;
public string Message { get; init; } = string.Empty;
public string RawMessage { get; init; } = string.Empty;
public string ColorHex { get; init; } = "#53FC18";
}
/// <summary>
/// Kick.com sohbetinin Pusher WebSocket protokolüne bağlanan istemci.
/// .NET'in ClientWebSocket'i tek bir dedike okuma döngüsünde asenkron
/// olarak kullanıldığından, Python tarafındaki gibi çoklu iş parçacığı
/// çakışması riski yoktur. Bağlantı koptuğunda üstel geri çekilmeyle
/// (exponential backoff) otomatik olarak yeniden bağlanır.
/// </summary>
public sealed partial class PusherChatService : IAsyncDisposable
{
private const string PusherAppKey = "32cbd69e4b950bf97679";
private const string PusherCluster = "us2";
[GeneratedRegex(@"\[emote:\d+:([^\]]+)\]")]
private static partial Regex KickEmoteRegex();
private readonly SemaphoreSlim _sendLock = new(1, 1);
private ClientWebSocket? _socket;
private CancellationTokenSource? _cts;
private Task? _receiveLoopTask;
private long _chatroomId;
private int _reconnectAttempt;
public event EventHandler<ChatMessageEventArgs>? MessageReceived;
public event EventHandler<bool>? ConnectionStateChanged;
public async Task ConnectAsync(long chatroomId)
{
await DisconnectAsync().ConfigureAwait(false);
_chatroomId = chatroomId;
_cts = new CancellationTokenSource();
_receiveLoopTask = RunConnectionLoopAsync(_cts.Token);
}
public async Task DisconnectAsync()
{
try
{
_cts?.Cancel();
if (_socket is { State: WebSocketState.Open })
{
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "closing", CancellationToken.None)
.ConfigureAwait(false);
}
}
catch
{
// kapatma sırasında oluşan hatalar yoksayılır
}
finally
{
_socket?.Dispose();
_socket = null;
if (_receiveLoopTask != null)
{
try { await _receiveLoopTask.ConfigureAwait(false); } catch { /* yoksay */ }
}
}
}
private async Task RunConnectionLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await ConnectOnceAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
LoggingService.Instance.Warning($"Sohbet bağlantısı kesildi: {ex.Message}");
}
ConnectionStateChanged?.Invoke(this, false);
if (ct.IsCancellationRequested) break;
_reconnectAttempt++;
var delay = TimeSpan.FromSeconds(Math.Min(30, Math.Pow(2, _reconnectAttempt)));
try { await Task.Delay(delay, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
private async Task ConnectOnceAsync(CancellationToken ct)
{
_socket = new ClientWebSocket();
var uri = new Uri($"wss://ws-{PusherCluster}.pusher.com/app/{PusherAppKey}?protocol=7&client=js&version=8.4.0&flash=false");
await _socket.ConnectAsync(uri, ct).ConfigureAwait(false);
_reconnectAttempt = 0;
ConnectionStateChanged?.Invoke(this, true);
var buffer = new byte[16384];
var messageBuilder = new StringBuilder();
using var pingCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var pingTask = RunPingLoopAsync(pingCts.Token);
try
{
while (_socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
{
messageBuilder.Clear();
WebSocketReceiveResult result;
do
{
result = await _socket.ReceiveAsync(new ArraySegment<byte>(buffer), ct).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close) return;
messageBuilder.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));
} while (!result.EndOfMessage);
await HandleRawMessageAsync(messageBuilder.ToString(), ct).ConfigureAwait(false);
}
}
finally
{
pingCts.Cancel();
try { await pingTask.ConfigureAwait(false); } catch { }
}
}
private async Task RunPingLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
if (_socket is { State: WebSocketState.Open })
{
await SendAsync("{\"event\":\"pusher:ping\",\"data\":{}}", ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
LoggingService.Instance.Warning($"Sohbet ping gönderilemedi: {ex.Message}");
}
}
}
private async Task HandleRawMessageAsync(string raw, CancellationToken ct)
{
try
{
using var doc = JsonDocument.Parse(raw);
var root = doc.RootElement;
var eventName = root.TryGetProperty("event", out var evEl) ? evEl.GetString() : null;
switch (eventName)
{
case "pusher:connection_established":
await SubscribeToChatroomAsync(ct).ConfigureAwait(false);
break;
case "App\\Events\\ChatMessageEvent":
case "ChatMessageEvent":
HandleChatMessagePayload(root);
break;
case "pusher:ping":
await SendAsync("{\"event\":\"pusher:pong\",\"data\":{}}", ct).ConfigureAwait(false);
break;
}
}
catch (JsonException ex)
{
LoggingService.Instance.Warning($"Sohbet mesajı ayrıştırılamadı: {ex.Message}");
}
}
private void HandleChatMessagePayload(JsonElement root)
{
if (!root.TryGetProperty("data", out var dataEl)) return;
var dataRaw = dataEl.GetString();
if (string.IsNullOrEmpty(dataRaw)) return;
using var innerDoc = JsonDocument.Parse(dataRaw);
var inner = innerDoc.RootElement;
var rawContent = inner.TryGetProperty("content", out var c) ? c.GetString() ?? string.Empty : string.Empty;
var content = KickEmoteRegex().Replace(rawContent, ":$1:");
var sender = inner.TryGetProperty("sender", out var s) ? s : default;
var username = "?";
var color = "#53FC18";
if (sender.ValueKind == JsonValueKind.Object)
{
if (sender.TryGetProperty("username", out var u)) username = u.GetString() ?? "?";
if (sender.TryGetProperty("identity", out var identity) &&
identity.TryGetProperty("color", out var colorEl))
{
var parsedColor = colorEl.GetString();
if (!string.IsNullOrWhiteSpace(parsedColor))
color = parsedColor;
}
}
MessageReceived?.Invoke(this, new ChatMessageEventArgs
{
Username = username,
Message = content,
RawMessage = rawContent,
ColorHex = color,
});
}
private async Task SubscribeToChatroomAsync(CancellationToken ct)
{
var channelName = $"chatrooms.{_chatroomId}.v2";
var payload = JsonSerializer.Serialize(new
{
@event = "pusher:subscribe",
data = new { auth = "", channel = channelName },
});
await SendAsync(payload, ct).ConfigureAwait(false);
}
private async Task SendAsync(string json, CancellationToken ct)
{
if (_socket is not { State: WebSocketState.Open }) return;
await _sendLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_socket is not { State: WebSocketState.Open }) return;
var bytes = Encoding.UTF8.GetBytes(json);
await _socket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, ct)
.ConfigureAwait(false);
}
finally
{
_sendLock.Release();
}
}
public async ValueTask DisposeAsync()
{
await DisconnectAsync().ConfigureAwait(false);
_cts?.Dispose();
_sendLock.Dispose();
}
}

View file

@ -0,0 +1,82 @@
using System.IO;
using System.Media;
namespace KickStreamHub.Services;
/// <summary>
/// Canlı yayın başlangıcı, kategori değişikliği ve anahtar kelime uyarıları için
/// sesli bildirim çalar. Özel .wav dosyası seçilmemişse bellekte yumuşak çift tonlu
/// bir bildirim sesi (chime) üretip çalar.
/// </summary>
public static class SoundService
{
private static readonly byte[] DefaultChimeWav = GeneratePleasantChimeWav(587.33, 880.0, 260); // D5 -> A5
private static readonly byte[] KeywordAlertWav = GeneratePleasantChimeWav(659.25, 1046.50, 300); // E5 -> C6
public static void PlayNotification(string? customSoundPath = null, bool isKeywordOrCategoryAlert = false)
{
Task.Run(() =>
{
try
{
if (!string.IsNullOrWhiteSpace(customSoundPath) && File.Exists(customSoundPath))
{
using var player = new SoundPlayer(customSoundPath);
player.PlaySync();
return;
}
var wavBytes = isKeywordOrCategoryAlert ? KeywordAlertWav : DefaultChimeWav;
using var ms = new MemoryStream(wavBytes);
using var chimePlayer = new SoundPlayer(ms);
chimePlayer.PlaySync();
}
catch (Exception ex)
{
LoggingService.Instance.Warning($"Bildirim sesi çalınamadı: {ex.Message}");
}
});
}
private static byte[] GeneratePleasantChimeWav(double freq1, double freq2, int durationMs)
{
const int sampleRate = 44100;
int totalSamples = sampleRate * durationMs / 1000;
int halfSamples = totalSamples / 2;
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
int dataSize = totalSamples * 2;
bw.Write("RIFF"u8.ToArray());
bw.Write(36 + dataSize);
bw.Write("WAVE"u8.ToArray());
bw.Write("fmt "u8.ToArray());
bw.Write(16);
bw.Write((short)1); // PCM
bw.Write((short)1); // Mono
bw.Write(sampleRate);
bw.Write(sampleRate * 2);
bw.Write((short)2);
bw.Write((short)16);
bw.Write("data"u8.ToArray());
bw.Write(dataSize);
for (int i = 0; i < totalSamples; i++)
{
double freq = i < halfSamples ? freq1 : freq2;
int localIndex = i < halfSamples ? i : i - halfSamples;
int localLen = i < halfSamples ? halfSamples : totalSamples - halfSamples;
double t = (double)localIndex / sampleRate;
double envelope = Math.Exp(-4.5 * localIndex / localLen);
if (localIndex < 200) envelope *= localIndex / 200.0;
double sample = Math.Sin(2 * Math.PI * freq * t) * 0.35 * envelope;
short pcm = (short)(sample * short.MaxValue);
bw.Write(pcm);
}
return ms.ToArray();
}
}

View file

@ -0,0 +1,59 @@
using System.Diagnostics;
using System.IO;
using Microsoft.Win32;
namespace KickStreamHub.Services;
public static class StartupService
{
private const string AppName = "LDKickWatch";
private const string LegacyAppName = "KickStreamHub";
private const string RunRegistryKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
public static void SetRunOnStartup(bool enable)
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RunRegistryKey, writable: true);
if (key == null) return;
if (key.GetValue(LegacyAppName) != null)
{
key.DeleteValue(LegacyAppName, throwOnMissingValue: false);
}
if (enable)
{
var exePath = Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule?.FileName;
if (!string.IsNullOrEmpty(exePath) && File.Exists(exePath))
{
key.SetValue(AppName, $"\"{exePath}\"");
}
}
else
{
if (key.GetValue(AppName) != null)
{
key.DeleteValue(AppName, throwOnMissingValue: false);
}
}
}
catch (Exception ex)
{
LoggingService.Instance.Warning($"Başlangıçta çalıştırma ayarı güncellenemedi: {ex.Message}");
}
}
public static bool IsRunOnStartup()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RunRegistryKey, writable: false);
return key?.GetValue(AppName) != null;
}
catch
{
return false;
}
}
}

View file

@ -0,0 +1,288 @@
using System.Diagnostics;
using System.IO;
namespace KickStreamHub.Services;
/// <summary>
/// Streamlink + oynatıcı (Pencere İçi VLC, Harici VLC, Harici MPV) işlemlerini bulan, başlatan ve
/// izleyen servis.
/// </summary>
public sealed class StreamlinkService
{
private readonly Dictionary<string, Process> _activeProcesses = new(StringComparer.OrdinalIgnoreCase);
private Process? _embeddedVlcProcess;
private string? _embeddedVlcChannel;
private readonly object _lock = new();
public event EventHandler<string>? ProcessExited;
public string? FindStreamlink(string? configuredPath)
{
if (!string.IsNullOrWhiteSpace(configuredPath) && File.Exists(configuredPath))
return configuredPath;
var candidates = new List<string>
{
"streamlink.exe",
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Streamlink", "bin", "streamlink.exe"),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Streamlink", "bin", "streamlink.exe"),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Streamlink", "bin", "streamlink.exe"),
};
foreach (var candidate in candidates)
{
var resolved = ResolveFromPathOrFile(candidate);
if (resolved != null) return resolved;
}
return null;
}
public string? FindPlayer(string playerChoice, string? configuredPath)
{
if (!string.IsNullOrWhiteSpace(configuredPath) && File.Exists(configuredPath))
return configuredPath;
bool isMpv = playerChoice.Equals("mpv", StringComparison.OrdinalIgnoreCase);
var names = isMpv ? new[] { "mpv.exe" } : new[] { "vlc.exe" };
var programFiles = new[]
{
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
};
foreach (var name in names)
{
var resolved = ResolveFromPathOrFile(name);
if (resolved != null) return resolved;
foreach (var pf in programFiles)
{
var candidate = Path.Combine(pf, isMpv ? "mpv" : "VideoLAN\\VLC", name);
if (File.Exists(candidate)) return candidate;
}
}
return null;
}
private static string? ResolveFromPathOrFile(string nameOrPath)
{
if (File.Exists(nameOrPath)) return Path.GetFullPath(nameOrPath);
var pathEnv = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
foreach (var dir in pathEnv.Split(Path.PathSeparator))
{
try
{
var full = Path.Combine(dir, nameOrPath);
if (File.Exists(full)) return full;
}
catch
{
// geçersiz path parçalarını yoksay
}
}
return null;
}
public bool IsPlaying(string channelName)
{
lock (_lock)
{
if (_embeddedVlcProcess is { HasExited: false } &&
string.Equals(_embeddedVlcChannel, channelName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (_activeProcesses.TryGetValue(channelName, out var proc))
{
if (!proc.HasExited) return true;
_activeProcesses.Remove(channelName);
}
return false;
}
}
/// <summary>
/// VLC'yi doğrudan uygulama penceresi içindeki WinForms Panel HWND'sine (--drawable-hwnd) gömer.
/// Streamlink kuruluysa Streamlink üzerinden, kurulu değilse Kick HLS playback_url üzerinden başlatır.
/// </summary>
public (bool success, string message) PlayEmbeddedVlc(
string channelName,
IntPtr hwnd,
string? streamlinkPath,
string vlcPath,
string quality,
string? playbackUrl,
string? extraArgs = null)
{
StopEmbeddedVlc();
try
{
ProcessStartInfo psi;
string vlcEmbedFlags = $"-I dummy --dummy-quiet --drawable-hwnd={hwnd.ToInt64()} --no-video-title-show --mouse-hide-timeout=1000";
if (!string.IsNullOrWhiteSpace(streamlinkPath) && File.Exists(streamlinkPath))
{
var url = $"https://kick.com/{channelName}";
var args = $"\"{url}\" {quality} --player \"{vlcPath}\" --player-args \"{vlcEmbedFlags}\"";
if (!string.IsNullOrWhiteSpace(extraArgs))
args += $" {extraArgs.Trim()}";
psi = new ProcessStartInfo
{
FileName = streamlinkPath,
Arguments = args,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
}
else if (!string.IsNullOrWhiteSpace(playbackUrl))
{
psi = new ProcessStartInfo
{
FileName = vlcPath,
Arguments = $"\"{playbackUrl}\" {vlcEmbedFlags}",
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
}
else
{
return (false, "⚠ Pencere içi VLC için Streamlink kurulu olmalı veya kanal canlı yayında olmalıdır.");
}
var process = Process.Start(psi);
if (process is null) return (false, "Pencere içi VLC başlatılamadı.");
process.EnableRaisingEvents = true;
process.Exited += (_, _) =>
{
lock (_lock)
{
if (ReferenceEquals(_embeddedVlcProcess, process))
{
_embeddedVlcProcess = null;
_embeddedVlcChannel = null;
}
}
ProcessExited?.Invoke(this, channelName);
};
lock (_lock)
{
_embeddedVlcProcess = process;
_embeddedVlcChannel = channelName;
}
return (true, $"🎬 {channelName.ToUpperInvariant()} yayını Pencere İçi VLC oynatıcıda başlatıldı.");
}
catch (Exception ex)
{
LoggingService.Instance.Error($"Pencere içi VLC başlatılamadı ({channelName})", ex);
return (false, $"VLC Hatası: {ex.Message}");
}
}
public void StopEmbeddedVlc()
{
lock (_lock)
{
if (_embeddedVlcProcess != null)
{
try { if (!_embeddedVlcProcess.HasExited) _embeddedVlcProcess.Kill(true); } catch { }
_embeddedVlcProcess = null;
_embeddedVlcChannel = null;
}
}
}
public (bool success, string message) Play(string channelName, string streamlinkPath, string playerPath, string quality, string? extraArgs = null)
{
lock (_lock)
{
if (_activeProcesses.TryGetValue(channelName, out var existing) && !existing.HasExited)
{
try { existing.Kill(true); } catch { /* yoksay */ }
_activeProcesses.Remove(channelName);
return (true, "Yayın durduruldu.");
}
}
try
{
var url = $"https://kick.com/{channelName}";
var args = $"\"{url}\" {quality} --player \"{playerPath}\" --title \"{channelName} - LD KickWatch\"";
if (!string.IsNullOrWhiteSpace(extraArgs))
{
args += $" {extraArgs.Trim()}";
}
var psi = new ProcessStartInfo
{
FileName = streamlinkPath,
Arguments = args,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
var process = Process.Start(psi);
if (process is null) return (false, "İşlem başlatılamadı.");
process.EnableRaisingEvents = true;
process.Exited += (_, _) =>
{
lock (_lock)
{
_activeProcesses.Remove(channelName);
}
ProcessExited?.Invoke(this, channelName);
};
lock (_lock)
{
_activeProcesses[channelName] = process;
}
return (true, $"{channelName.ToUpperInvariant()} yayını harici oynatıcıda başlatılıyor...");
}
catch (Exception ex)
{
LoggingService.Instance.Error($"Yayın başlatılamadı ({channelName})", ex);
return (false, $"Hata: {ex.Message}");
}
}
public void Stop(string channelName)
{
lock (_lock)
{
if (string.Equals(_embeddedVlcChannel, channelName, StringComparison.OrdinalIgnoreCase))
{
StopEmbeddedVlc();
}
if (_activeProcesses.TryGetValue(channelName, out var proc))
{
try { if (!proc.HasExited) proc.Kill(true); } catch { }
_activeProcesses.Remove(channelName);
}
}
}
public void StopAll()
{
StopEmbeddedVlc();
lock (_lock)
{
foreach (var proc in _activeProcesses.Values)
{
try { if (!proc.HasExited) proc.Kill(true); } catch { /* yoksay */ }
}
_activeProcesses.Clear();
}
}
}

View file

@ -0,0 +1,44 @@
using CommunityToolkit.Mvvm.ComponentModel;
using KickStreamHub.Models;
namespace KickStreamHub.ViewModels;
public partial class ChannelCardViewModel : ObservableObject
{
[ObservableProperty] private string _channelName;
[ObservableProperty] private string _groupName = string.Empty;
[ObservableProperty] private bool _isLive;
[ObservableProperty] private string _title = "Durum kontrol ediliyor...";
[ObservableProperty] private string _category = string.Empty;
[ObservableProperty] private long _viewers;
[ObservableProperty] private bool _verified;
[ObservableProperty] private string? _avatarPath;
[ObservableProperty] private bool _isVisible = true;
[ObservableProperty] private bool _isPlaying;
public ChannelCardViewModel(string channelName, string groupName = "")
{
_channelName = channelName;
_groupName = groupName;
}
public void ApplyStatus(ChannelStatus status)
{
IsLive = status.IsLive;
Title = status.IsLive
? (string.IsNullOrWhiteSpace(status.Title) ? "Canlı Yayında" : status.Title)
: "Şu anda çevrimdışı";
Category = status.Category;
Viewers = status.Viewers;
Verified = status.Verified;
OnPropertyChanged(nameof(ViewersDisplay));
OnPropertyChanged(nameof(StatusText));
OnPropertyChanged(nameof(SubText));
}
public string ViewersDisplay => Viewers >= 1000 ? $"{Viewers / 1000.0:0.0}B" : Viewers.ToString();
public string StatusText => IsLive ? "● CANLI" : "KAPALI";
public string SubText => IsLive
? $"{(string.IsNullOrEmpty(Category) ? "Canlı Yayın" : $"🎮 {Category}")} • 👥 {ViewersDisplay} izleyici"
: "Yayında değil";
}

View file

@ -0,0 +1,134 @@
using System.Collections.ObjectModel;
using System.Windows.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using KickStreamHub.Services;
namespace KickStreamHub.ViewModels;
public class ChatMessageItem
{
public string Username { get; init; } = string.Empty;
public string Message { get; init; } = string.Empty;
public string RawMessage { get; init; } = string.Empty;
public string ColorHex { get; init; } = "#53FC18";
public DateTime Timestamp { get; init; } = DateTime.Now;
public string TimeFormatted => Timestamp.ToString("HH:mm");
}
public partial class ChatViewModel : ObservableObject, IAsyncDisposable
{
private readonly PusherChatService _chatService = new();
private readonly Dispatcher _dispatcher;
public int MaxMessages { get; set; } = 500;
[ObservableProperty] private string _channelName = string.Empty;
[ObservableProperty] private long _chatroomId;
[ObservableProperty] private bool _isConnected;
[ObservableProperty] private bool _isPaused;
[ObservableProperty] private string _filterText = string.Empty;
[ObservableProperty] private double _fontSize = 13;
[ObservableProperty] private double _backgroundOpacity = 1.0;
[ObservableProperty] private bool _isTopMost;
[ObservableProperty] private int _messageCount;
public ObservableCollection<ChatMessageItem> Messages { get; } = new();
public ObservableCollection<ChatMessageItem> FilteredMessages { get; } = new();
public ChatViewModel()
{
_dispatcher = Dispatcher.CurrentDispatcher;
_chatService.MessageReceived += OnMessageReceived;
_chatService.ConnectionStateChanged += (_, connected) =>
_dispatcher.BeginInvoke(() => IsConnected = connected);
}
public async Task ConnectAsync(string channelName, long chatroomId)
{
if (IsConnected && ChatroomId == chatroomId && string.Equals(ChannelName, channelName, StringComparison.OrdinalIgnoreCase))
return;
ChannelName = channelName;
ChatroomId = chatroomId;
Messages.Clear();
FilteredMessages.Clear();
MessageCount = 0;
if (chatroomId > 0)
await _chatService.ConnectAsync(chatroomId);
}
public async Task DisconnectAsync()
{
await _chatService.DisconnectAsync();
IsConnected = false;
}
private void OnMessageReceived(object? sender, ChatMessageEventArgs e)
{
var item = new ChatMessageItem
{
Username = e.Username,
Message = e.Message,
RawMessage = string.IsNullOrEmpty(e.RawMessage) ? e.Message : e.RawMessage,
ColorHex = e.ColorHex,
};
_dispatcher.BeginInvoke(() =>
{
Messages.Add(item);
while (Messages.Count > MaxMessages)
Messages.RemoveAt(0);
MessageCount = Messages.Count;
if (!IsPaused && MatchesFilter(item))
{
FilteredMessages.Add(item);
while (FilteredMessages.Count > MaxMessages)
FilteredMessages.RemoveAt(0);
}
});
}
private bool MatchesFilter(ChatMessageItem item)
{
if (string.IsNullOrWhiteSpace(FilterText)) return true;
var q = FilterText.Trim();
return item.Username.Contains(q, StringComparison.OrdinalIgnoreCase) ||
item.Message.Contains(q, StringComparison.OrdinalIgnoreCase);
}
partial void OnFilterTextChanged(string value) => RebuildFilteredMessages();
partial void OnIsPausedChanged(bool value)
{
if (!value)
RebuildFilteredMessages();
}
private void RebuildFilteredMessages()
{
FilteredMessages.Clear();
foreach (var msg in Messages)
{
if (MatchesFilter(msg))
FilteredMessages.Add(msg);
}
}
[RelayCommand]
private void TogglePause() => IsPaused = !IsPaused;
[RelayCommand]
private void ClearMessages()
{
Messages.Clear();
FilteredMessages.Clear();
MessageCount = 0;
}
public async ValueTask DisposeAsync()
{
await _chatService.DisposeAsync();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace KickStreamHub.ViewModels;
public partial class MultiStreamSlotViewModel : ObservableObject
{
public int SlotIndex { get; init; }
public string SlotTitle => $"Ekran #{SlotIndex + 1}";
[ObservableProperty] private string _channelName = string.Empty;
[ObservableProperty] private bool _isActive;
[ObservableProperty] private bool _isMuted = true;
}

View file

@ -0,0 +1,119 @@
<Window x:Class="KickStreamHub.Views.ChatWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:helpers="clr-namespace:KickStreamHub.Helpers"
Title="{Binding ChannelName, StringFormat='{}{0} — Canlı Sohbet (LD KickWatch)'}"
Icon="pack://application:,,,/Resources/app.ico"
Height="680" Width="430" MinWidth="320" MinHeight="420"
WindowStartupLocation="CenterScreen"
Topmost="{Binding IsTopMost}" ResizeMode="CanResizeWithGrip"
Opacity="{Binding BackgroundOpacity}"
Background="#060A10">
<Grid Margin="12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Row 0: Chat Header -->
<Border Grid.Row="0" Background="#0D141F" CornerRadius="10" Padding="12,8" Margin="0,0,0,8" BorderBrush="#1C283B" BorderThickness="1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock FontSize="15" FontWeight="ExtraBold" Foreground="#53FC18"
Text="{Binding ChannelName, StringFormat='💬 {0}'}" VerticalAlignment="Center" />
<Border Background="#152234" CornerRadius="6" Padding="7,2" Margin="10,0,0,0" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal">
<Ellipse Width="7" Height="7" Margin="0,0,5,0" VerticalAlignment="Center"
Fill="{Binding IsConnected, Converter={StaticResource LiveToBrush}}" />
<TextBlock Foreground="#CBD5E1" FontSize="10.5" FontWeight="SemiBold" VerticalAlignment="Center"
Text="{Binding IsConnected, Converter={StaticResource ChatConnTextConverter}}" />
</StackPanel>
</Border>
</StackPanel>
<CheckBox Grid.Column="1" Content="📌 Üstte Tut" Foreground="#CBD5E1" FontSize="11.5" VerticalAlignment="Center"
IsChecked="{Binding IsTopMost}" ToolTip="Pencereyi her zaman üstte tut" />
</Grid>
</Border>
<!-- Row 1: Filter & Controls -->
<Grid Grid.Row="1" Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Margin="0,0,6,0" FontSize="12"
Tag="🔍 Mesaj veya kullanıcı ara..."
Text="{Binding FilterText, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Column="1" Content="{Binding IsPaused, Converter={StaticResource PauseTextConverter}}"
Style="{StaticResource SecondaryButton}" Margin="0,0,5,0"
Command="{Binding TogglePauseCommand}" Padding="10,6" FontSize="11" />
<Button Grid.Column="2" Content="🗑" Style="{StaticResource DangerButton}"
Command="{Binding ClearMessagesCommand}" Padding="9,6" FontSize="11" ToolTip="Sohbeti Temizle" />
</Grid>
<!-- Row 2: Messages List -->
<Border Grid.Row="2" Background="#0A0F17" BorderBrush="#1A2638" BorderThickness="1" CornerRadius="10" Padding="4">
<ListBox x:Name="ChatListBox"
ItemsSource="{Binding FilteredMessages}"
Background="Transparent" BorderThickness="0"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.CanContentScroll="False"
VirtualizingPanel.ScrollUnit="Pixel">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Background="#0E1520" CornerRadius="6" Padding="8,5" Margin="2,2">
<TextBlock TextWrapping="Wrap"
FontSize="{Binding DataContext.FontSize, RelativeSource={RelativeSource AncestorType=Window}}"
helpers:RichChatHelper.MessageItem="{Binding}" />
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Padding" Value="0" />
<Setter Property="Margin" Value="0" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Focusable" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Border>
<!-- Row 3: Font & Opacity Sliders -->
<Border Grid.Row="3" Background="#0D141F" CornerRadius="8" Padding="10,7" Margin="0,8,0,0" BorderBrush="#1C283B" BorderThickness="1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="🔠 Boyut:" Foreground="#94A3B8" FontSize="11" VerticalAlignment="Center" Margin="0,0,6,0" />
<Slider Grid.Column="1" Minimum="10" Maximum="22" Value="{Binding FontSize}"
TickFrequency="1" IsSnapToTickEnabled="True" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="👁 Saydamlık:" Foreground="#94A3B8" FontSize="11"
VerticalAlignment="Center" Margin="12,0,6,0" />
<Slider Grid.Column="3" Minimum="0.35" Maximum="1.0" Value="{Binding BackgroundOpacity}"
TickFrequency="0.05" IsSnapToTickEnabled="True" VerticalAlignment="Center" />
</Grid>
</Border>
</Grid>
</Window>

View file

@ -0,0 +1,33 @@
using System.Collections.Specialized;
using System.Windows;
using KickStreamHub.ViewModels;
namespace KickStreamHub.Views;
public partial class ChatWindow : Window
{
private readonly ChatViewModel _vm;
public ChatWindow(string channelName, long chatroomId, int maxMessages = 500)
{
InitializeComponent();
_vm = new ChatViewModel { MaxMessages = maxMessages };
DataContext = _vm;
Loaded += async (_, _) => await _vm.ConnectAsync(channelName, chatroomId);
Closed += async (_, _) => await _vm.DisposeAsync();
_vm.FilteredMessages.CollectionChanged += AutoScrollToBottom;
}
private void AutoScrollToBottom(object? sender, NotifyCollectionChangedEventArgs e)
{
if (_vm.IsPaused) return;
if ((e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Reset)
&& ChatListBox.Items.Count > 0)
{
ChatListBox.ScrollIntoView(ChatListBox.Items[^1]);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,501 @@
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using KickStreamHub.Services;
using KickStreamHub.ViewModels;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
using SaveFileDialog = Microsoft.Win32.SaveFileDialog;
namespace KickStreamHub.Views;
public partial class MainWindow : Window
{
private readonly MainViewModel _viewModel;
private readonly NotificationService _notifications;
private bool _isWebViewInitialized;
private readonly bool[] _isMultiWebViewInitialized = new bool[4];
private CoreWebView2Environment? _webViewEnv;
private WindowState _stateBeforeFullScreen = WindowState.Normal;
public MainWindow()
{
InitializeComponent();
VlcPanel.BackColor = System.Drawing.Color.FromArgb(4, 9, 15);
_viewModel = new MainViewModel();
_notifications = new NotificationService();
_viewModel.Notifications = _notifications;
DataContext = _viewModel;
_viewModel.EmbeddedPlayRequested += ViewModel_EmbeddedPlayRequested;
_viewModel.EmbeddedVlcPlayRequested += ViewModel_EmbeddedVlcPlayRequested;
_viewModel.EmbeddedStopRequested += ViewModel_EmbeddedStopRequested;
_viewModel.EmbeddedMuteRequested += ViewModel_EmbeddedMuteRequested;
_viewModel.EmbeddedReloadRequested += ViewModel_EmbeddedReloadRequested;
_viewModel.FullScreenChanged += ViewModel_FullScreenChanged;
_viewModel.MultiSlotPlayRequested += ViewModel_MultiSlotPlayRequested;
_viewModel.MultiSlotStopRequested += ViewModel_MultiSlotStopRequested;
_viewModel.MultiSlotMuteRequested += ViewModel_MultiSlotMuteRequested;
_viewModel.EmbeddedChat.FilteredMessages.CollectionChanged += EmbeddedChat_CollectionChanged;
_notifications.OpenRequested += (_, _) => RestoreAndBringToFront();
_notifications.ExitRequested += (_, _) => Close();
_notifications.Show();
Loaded += (_, _) => _viewModel.Start();
StateChanged += MainWindow_StateChanged;
Closing += MainWindow_Closing;
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
RestoreWindowBounds();
var ctrlF = new KeyBinding(new RelayFocusCommand(this), Key.F, ModifierKeys.Control);
InputBindings.Add(ctrlF);
}
private async Task<CoreWebView2Environment> GetOrCreateWebViewEnvAsync()
{
if (_webViewEnv != null) return _webViewEnv;
var userDataFolder = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"LDKickWatch", "WebView2");
Directory.CreateDirectory(userDataFolder);
_webViewEnv = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
return _webViewEnv;
}
private void ViewModel_EmbeddedPlayRequested(object? sender, string channelName)
{
_ = Dispatcher.InvokeAsync(async () =>
{
try
{
if (!_isWebViewInitialized)
{
var env = await GetOrCreateWebViewEnvAsync();
await EmbeddedPlayer.EnsureCoreWebView2Async(env);
EmbeddedPlayer.CoreWebView2.Settings.IsStatusBarEnabled = false;
EmbeddedPlayer.CoreWebView2.Settings.AreDevToolsEnabled = false;
EmbeddedPlayer.CoreWebView2.ContainsFullScreenElementChanged += (_, _) =>
{
_viewModel.SetFullScreenState(EmbeddedPlayer.CoreWebView2.ContainsFullScreenElement);
};
_isWebViewInitialized = true;
}
EmbeddedPlayer.CoreWebView2.IsMuted = false;
var playerUrl = $"https://player.kick.com/{channelName.ToLowerInvariant()}";
EmbeddedPlayer.Source = new Uri(playerUrl);
}
catch (Exception ex)
{
_viewModel.StatusMessage = $"Dahili oynatıcı hatası: {ex.Message}";
}
});
}
private void ViewModel_EmbeddedVlcPlayRequested(object? sender, string channelName)
{
_ = Dispatcher.InvokeAsync(() =>
{
try
{
if (_isWebViewInitialized)
{
EmbeddedPlayer.Source = new Uri("about:blank");
}
VlcHost.UpdateLayout();
var hwnd = VlcPanel.Handle;
var streamlinkPath = _viewModel.Streamlink.FindStreamlink(_viewModel.Config.StreamlinkPath);
var vlcPath = _viewModel.Streamlink.FindPlayer("vlc", _viewModel.Config.PlayerPath);
if (vlcPath is null)
{
_viewModel.StatusMessage = "⚠ VLC bulunamadı! Lütfen VLC kurun veya Ayarlardan yolunu seçin.";
return;
}
var status = _viewModel.GetStatus(channelName);
var (success, msg) = _viewModel.Streamlink.PlayEmbeddedVlc(
channelName,
hwnd,
streamlinkPath,
vlcPath,
_viewModel.Config.StreamQuality,
status?.PlaybackUrl,
_viewModel.Config.ExtraStreamlinkArgs);
_viewModel.StatusMessage = msg;
if (!success)
{
_viewModel.StopEmbeddedPlayer();
}
}
catch (Exception ex)
{
_viewModel.StatusMessage = $"Pencere içi VLC hatası: {ex.Message}";
}
});
}
private void ViewModel_EmbeddedStopRequested(object? sender, EventArgs e)
{
_ = Dispatcher.InvokeAsync(() =>
{
try
{
if (_isWebViewInitialized)
{
EmbeddedPlayer.Source = new Uri("about:blank");
}
}
catch { }
});
}
private void ViewModel_EmbeddedMuteRequested(object? sender, bool isMuted)
{
_ = Dispatcher.InvokeAsync(() =>
{
try
{
if (_isWebViewInitialized && EmbeddedPlayer.CoreWebView2 != null)
{
EmbeddedPlayer.CoreWebView2.IsMuted = isMuted;
}
}
catch { }
});
}
private void ViewModel_EmbeddedReloadRequested(object? sender, EventArgs e)
{
_ = Dispatcher.InvokeAsync(() =>
{
try
{
if (_isWebViewInitialized)
{
EmbeddedPlayer.Reload();
}
}
catch { }
});
}
private void ViewModel_FullScreenChanged(object? sender, bool enable)
{
Dispatcher.Invoke(() =>
{
if (enable)
{
_stateBeforeFullScreen = WindowState;
WindowStyle = WindowStyle.None;
ResizeMode = ResizeMode.NoResize;
WindowState = WindowState.Normal;
WindowState = WindowState.Maximized;
}
else
{
WindowStyle = WindowStyle.SingleBorderWindow;
ResizeMode = ResizeMode.CanResize;
WindowState = _stateBeforeFullScreen == WindowState.Minimized ? WindowState.Normal : _stateBeforeFullScreen;
}
});
}
private void VlcPanel_DoubleClick(object? sender, EventArgs e)
{
_viewModel.ToggleFullScreenCommand.Execute(null);
}
private void MainWindow_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Escape && _viewModel.IsFullScreen)
{
_viewModel.SetFullScreenState(false);
e.Handled = true;
}
}
// ==================== MULTI-STREAM WEBVIEW2 HANDLERS ====================
private WebView2? GetMultiWebView(int index) => index switch
{
0 => MultiWebView0,
1 => MultiWebView1,
2 => MultiWebView2,
3 => MultiWebView3,
_ => null,
};
private void ViewModel_MultiSlotPlayRequested(object? sender, MultiSlotPlayEventArgs e)
{
_ = Dispatcher.InvokeAsync(async () =>
{
var wv = GetMultiWebView(e.SlotIndex);
if (wv is null) return;
try
{
if (!_isMultiWebViewInitialized[e.SlotIndex])
{
var env = await GetOrCreateWebViewEnvAsync();
await wv.EnsureCoreWebView2Async(env);
wv.CoreWebView2.Settings.IsStatusBarEnabled = false;
wv.CoreWebView2.Settings.AreDevToolsEnabled = false;
wv.CoreWebView2.ContainsFullScreenElementChanged += (_, _) =>
{
_viewModel.SetFullScreenState(wv.CoreWebView2.ContainsFullScreenElement);
};
_isMultiWebViewInitialized[e.SlotIndex] = true;
}
wv.CoreWebView2.IsMuted = e.IsMuted;
wv.Source = new Uri($"https://player.kick.com/{e.ChannelName.ToLowerInvariant()}");
}
catch (Exception ex)
{
_viewModel.StatusMessage = $"Çoklu yayın #{e.SlotIndex + 1} hatası: {ex.Message}";
}
});
}
private void ViewModel_MultiSlotStopRequested(object? sender, int slotIndex)
{
_ = Dispatcher.InvokeAsync(() =>
{
var wv = GetMultiWebView(slotIndex);
if (wv is null || !_isMultiWebViewInitialized[slotIndex]) return;
try { wv.Source = new Uri("about:blank"); } catch { }
});
}
private void ViewModel_MultiSlotMuteRequested(object? sender, MultiSlotPlayEventArgs e)
{
_ = Dispatcher.InvokeAsync(() =>
{
var wv = GetMultiWebView(e.SlotIndex);
if (wv is null || !_isMultiWebViewInitialized[e.SlotIndex]) return;
try
{
if (wv.CoreWebView2 != null)
wv.CoreWebView2.IsMuted = e.IsMuted;
}
catch { }
});
}
// ==================== EMBEDDED CHAT AUTO-SCROLL ====================
private void EmbeddedChat_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (_viewModel.EmbeddedChat.IsPaused) return;
if ((e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Reset) &&
EmbeddedChatListBox.Items.Count > 0)
{
EmbeddedChatListBox.ScrollIntoView(EmbeddedChatListBox.Items[^1]);
}
}
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(MainViewModel.ActivePage) && _viewModel.ActivePage == "exit")
{
Close();
}
}
private void ChannelList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.OriginalSource is DependencyObject dep)
{
var current = dep;
while (current != null && current is not System.Windows.Controls.ListBoxItem)
{
if (current is System.Windows.Controls.Primitives.ButtonBase)
return;
current = VisualTreeHelper.GetParent(current);
}
}
if (_viewModel.SelectedChannel is not null)
{
_viewModel.PlayChannelCommand.Execute(_viewModel.SelectedChannel.ChannelName);
}
}
private void RestoreWindowBounds()
{
var cfg = _viewModel.Config;
if (cfg.WindowLeft >= 0 && cfg.WindowTop >= 0)
{
var isVisibleOnAnyScreen = System.Windows.Forms.Screen.AllScreens.Any(s =>
s.WorkingArea.IntersectsWith(new System.Drawing.Rectangle(
(int)cfg.WindowLeft, (int)cfg.WindowTop,
(int)Math.Max(100, cfg.WindowWidth), (int)Math.Max(100, cfg.WindowHeight))));
if (isVisibleOnAnyScreen)
{
Left = cfg.WindowLeft;
Top = cfg.WindowTop;
}
}
if (cfg.WindowWidth >= MinWidth) Width = cfg.WindowWidth;
if (cfg.WindowHeight >= MinHeight) Height = cfg.WindowHeight;
if (cfg.StartMinimized)
{
WindowState = WindowState.Minimized;
if (cfg.MinimizeToTray)
{
Hide();
}
}
}
private void MainWindow_StateChanged(object? sender, EventArgs e)
{
if (WindowState == WindowState.Minimized && _viewModel.Config.MinimizeToTray)
Hide();
}
public void RestoreAndBringToFront()
{
Show();
if (WindowState == WindowState.Minimized)
WindowState = WindowState.Normal;
Activate();
Topmost = true;
Topmost = false;
Focus();
}
private void MainWindow_Closing(object? sender, CancelEventArgs e)
{
// Pencere kapatıldığında (X veya Alt+F4) uygulama arkaplanda açık kalmaz,
// tüm oynatıcı/WebView2/sohbet süreçlerini temizleyip tamamen kapanır.
var bounds = WindowState == WindowState.Normal ? new Rect(Left, Top, Width, Height) : RestoreBounds;
if (!bounds.IsEmpty && bounds.Width > 0 && bounds.Height > 0)
{
_viewModel.Config.WindowLeft = bounds.Left;
_viewModel.Config.WindowTop = bounds.Top;
_viewModel.Config.WindowWidth = bounds.Width;
_viewModel.Config.WindowHeight = bounds.Height;
}
_viewModel.Stop();
_notifications.Dispose();
try { EmbeddedPlayer.Dispose(); } catch { }
try { MultiWebView0.Dispose(); } catch { }
try { MultiWebView1.Dispose(); } catch { }
try { MultiWebView2.Dispose(); } catch { }
try { MultiWebView3.Dispose(); } catch { }
try { VlcHost.Dispose(); } catch { }
System.Windows.Application.Current.Shutdown();
}
private void BrowseStreamlink_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog
{
Filter = "Streamlink|streamlink.exe|Tüm Dosyalar|*.*",
Title = "Streamlink Yolunu Seçin"
};
if (dlg.ShowDialog() == true)
{
_viewModel.Config.StreamlinkPath = dlg.FileName;
}
}
private void BrowsePlayer_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog
{
Filter = "Oynatıcı Yürütülebilir Dosyası|*.exe|Tüm Dosyalar|*.*",
Title = "Oynatıcı (VLC/MPV) Yolunu Seçin"
};
if (dlg.ShowDialog() == true)
{
_viewModel.Config.PlayerPath = dlg.FileName;
}
}
private void BrowseSound_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog
{
Filter = "WAV Ses Dosyası|*.wav|Tüm Dosyalar|*.*",
Title = "Bildirim Ses Dosyasını (.wav) Seçin"
};
if (dlg.ShowDialog() == true)
{
_viewModel.Config.CustomSoundPath = dlg.FileName;
}
}
private void ExportFavorites_Click(object sender, RoutedEventArgs e)
{
var dlg = new SaveFileDialog
{
Filter = "JSON Yedek Dosyası (*.json)|*.json|CSV Tablo Dosyası (*.csv)|*.csv",
FileName = $"LDKickWatch_Favoriler_{DateTime.Now:yyyyMMdd}.json",
Title = "Favori Kanalları Dışa Aktar"
};
if (dlg.ShowDialog() == true)
{
_viewModel.ExportFavoritesToFile(dlg.FileName);
}
}
private void ImportFavorites_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog
{
Filter = "Desteklenen Dosyalar (*.json;*.csv)|*.json;*.csv|JSON (*.json)|*.json|CSV (*.csv)|*.csv",
Title = "Favori Kanalları İçe Aktar"
};
if (dlg.ShowDialog() == true)
{
_viewModel.ImportFavoritesFromFile(dlg.FileName);
}
}
private void SaveSettings_Click(object sender, RoutedEventArgs e)
{
_viewModel.SaveConfig();
_viewModel.StatusMessage = "✔ Ayarlar kaydedildi ve uygulandı.";
_viewModel.ActivePage = "home";
}
private class RelayFocusCommand : ICommand
{
private readonly MainWindow _win;
public RelayFocusCommand(MainWindow win) => _win = win;
public bool CanExecute(object? parameter) => true;
public void Execute(object? parameter)
{
_win._viewModel.ActivePage = "home";
if (_win.FindName("SearchBox") is System.Windows.Controls.TextBox tb)
{
tb.Focus();
tb.SelectAll();
}
}
public event EventHandler? CanExecuteChanged { add { } remove { } }
}
}

View file

@ -0,0 +1,45 @@
<Window x:Class="KickStreamHub.Views.PlayerWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
Title="LD KickWatch — Canlı Yayın Oynatıcı" Height="720" Width="1140" MinWidth="480" MinHeight="340"
Icon="pack://application:,,,/Resources/app.ico"
WindowStartupLocation="CenterScreen"
KeyDown="PlayerWindow_KeyDown"
Background="#04090F">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Control Bar (Collapsed in Fullscreen) -->
<Border x:Name="TopBar" Grid.Row="0" Background="#0D141F" Padding="12,7" BorderBrush="#1C283B" BorderThickness="0,0,0,1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center">
<Ellipse Width="8" Height="8" Fill="#53FC18" Margin="0,0,8,0" VerticalAlignment="Center" />
<TextBlock x:Name="ChannelTitleText" FontWeight="ExtraBold" FontSize="13.5" Foreground="#F8FAFC" VerticalAlignment="Center" />
<TextBlock Text=" • F11 veya oynatıcı içinden Tam Ekran yapabilirsiniz" FontSize="11" Foreground="#64748B" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<CheckBox x:Name="TopMostCheck" Content="📌 Üstte Tut (PiP)" FontSize="11.5" Margin="0,0,12,0"
VerticalAlignment="Center" Checked="TopMostCheck_Changed" Unchecked="TopMostCheck_Changed" />
<Button x:Name="MuteBtn" Content="🔊 Sesi Kapat" Style="{StaticResource SecondaryButton}"
FontSize="11" Padding="9,4" Margin="0,0,6,0" Click="MuteBtn_Click" />
<Button Content="⟳ Yenile" Style="{StaticResource SecondaryButton}"
FontSize="11" Padding="9,4" Margin="0,0,6,0" Click="ReloadBtn_Click" />
<Button Content="⛶ Tam Ekran (F11)" Style="{StaticResource PrimaryButton}"
FontSize="11" Padding="10,4" Click="FullScreenBtn_Click" />
</StackPanel>
</Grid>
</Border>
<wv2:WebView2 Grid.Row="1" x:Name="WebView" DefaultBackgroundColor="#04090F" />
</Grid>
</Window>

View file

@ -0,0 +1,120 @@
using System.IO;
using System.Windows;
using System.Windows.Input;
using Microsoft.Web.WebView2.Core;
namespace KickStreamHub.Views;
public partial class PlayerWindow : Window
{
private readonly string _channelName;
private bool _isFullScreen;
private WindowState _previousState = WindowState.Normal;
public PlayerWindow(string channelName)
{
InitializeComponent();
_channelName = channelName;
Title = $"{channelName.ToUpperInvariant()} — Canlı Yayın (LD KickWatch)";
ChannelTitleText.Text = $"{channelName.ToUpperInvariant()} — LD KickWatch Oynatıcı";
Loaded += PlayerWindow_Loaded;
}
private async void PlayerWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
var userDataFolder = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"LDKickWatch", "WebView2");
Directory.CreateDirectory(userDataFolder);
var env = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
await WebView.EnsureCoreWebView2Async(env);
WebView.CoreWebView2.Settings.IsStatusBarEnabled = false;
WebView.CoreWebView2.Settings.AreDevToolsEnabled = false;
// HTML5 Video Tam Ekran (requestFullscreen) olayını yakala
WebView.CoreWebView2.ContainsFullScreenElementChanged += (_, _) =>
{
SetFullScreen(WebView.CoreWebView2.ContainsFullScreenElement);
};
var playerUrl = $"https://player.kick.com/{_channelName.ToLowerInvariant()}";
WebView.Source = new Uri(playerUrl);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show($"Oynatıcı başlatılamadı: {ex.Message}", "Hata", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void SetFullScreen(bool enable)
{
if (_isFullScreen == enable) return;
_isFullScreen = enable;
if (enable)
{
_previousState = WindowState;
TopBar.Visibility = Visibility.Collapsed;
WindowStyle = WindowStyle.None;
ResizeMode = ResizeMode.NoResize;
WindowState = WindowState.Normal; // WPF'de tam ekran geçişi için önce Normal sonra Maximized yapılır
WindowState = WindowState.Maximized;
}
else
{
TopBar.Visibility = Visibility.Visible;
WindowStyle = WindowStyle.SingleBorderWindow;
ResizeMode = ResizeMode.CanResize;
WindowState = _previousState == WindowState.Minimized ? WindowState.Normal : _previousState;
}
}
private void FullScreenBtn_Click(object sender, RoutedEventArgs e) => SetFullScreen(!_isFullScreen);
private void ReloadBtn_Click(object sender, RoutedEventArgs e)
{
try { WebView.Reload(); } catch { }
}
private void MuteBtn_Click(object sender, RoutedEventArgs e)
{
try
{
if (WebView.CoreWebView2 != null)
{
WebView.CoreWebView2.IsMuted = !WebView.CoreWebView2.IsMuted;
MuteBtn.Content = WebView.CoreWebView2.IsMuted ? "🔇 Sesi Aç" : "🔊 Sesi Kapat";
}
}
catch { }
}
private void TopMostCheck_Changed(object sender, RoutedEventArgs e)
{
Topmost = TopMostCheck.IsChecked == true;
}
private void PlayerWindow_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.F11)
{
SetFullScreen(!_isFullScreen);
e.Handled = true;
}
else if (e.Key == Key.Escape && _isFullScreen)
{
SetFullScreen(false);
e.Handled = true;
}
}
protected override void OnClosed(EventArgs e)
{
try { WebView.Dispose(); } catch { }
base.OnClosed(e);
}
}