commit acce34e346aa94f8ad01b9b6f0ecd5f0f5def88b Author: LilDosto Date: Tue Oct 27 22:11:06 2026 +0300 feat: LD KickWatch v1.2.0 - Full Studio Release (Embedded VLC, Multi-Stream 2x2, Split Chat, Kick Emotes, Audio & Keyword Alerts) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e29f35a --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/KickStreamHub.sln b/KickStreamHub.sln new file mode 100644 index 0000000..1732621 --- /dev/null +++ b/KickStreamHub.sln @@ -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 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..492631d --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3af1429 --- /dev/null +++ b/README.md @@ -0,0 +1,132 @@ +
+ +# 🟢 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) + +
+ +--- + +## 🚀 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. diff --git a/publish/LDKickWatch.exe b/publish/LDKickWatch.exe new file mode 100644 index 0000000..2fba30c Binary files /dev/null and b/publish/LDKickWatch.exe differ diff --git a/src/KickStreamHub/App.xaml b/src/KickStreamHub/App.xaml new file mode 100644 index 0000000..2ef6fae --- /dev/null +++ b/src/KickStreamHub/App.xaml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/KickStreamHub/App.xaml.cs b/src/KickStreamHub/App.xaml.cs new file mode 100644 index 0000000..c52c9cb --- /dev/null +++ b/src/KickStreamHub/App.xaml.cs @@ -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); + } +} diff --git a/src/KickStreamHub/Converters/StringToVisibilityConverter.cs b/src/KickStreamHub/Converters/StringToVisibilityConverter.cs new file mode 100644 index 0000000..c5ab20f --- /dev/null +++ b/src/KickStreamHub/Converters/StringToVisibilityConverter.cs @@ -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(); +} + +/// +/// Diskteki avatar dosyasını kilitlemeden (BitmapCacheOption.OnLoad) belleğe yükler. +/// Böylece AvatarCacheService dosyayı güncellerken IOException (file lock) oluşmaz. +/// +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 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(); +} diff --git a/src/KickStreamHub/Helpers/RichChatHelper.cs b/src/KickStreamHub/Helpers/RichChatHelper.cs new file mode 100644 index 0000000..5a0bae1 --- /dev/null +++ b/src/KickStreamHub/Helpers/RichChatHelper.cs @@ -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; + +/// +/// 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. +/// +public static partial class RichChatHelper +{ + [GeneratedRegex(@"\[emote:(\d+):([^\]]+)\]")] + private static partial Regex EmotePattern(); + + private static readonly ConcurrentDictionary 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ç + } + } +} diff --git a/src/KickStreamHub/KickStreamHub.csproj b/src/KickStreamHub/KickStreamHub.csproj new file mode 100644 index 0000000..35e5cef --- /dev/null +++ b/src/KickStreamHub/KickStreamHub.csproj @@ -0,0 +1,31 @@ + + + + WinExe + net8.0-windows + enable + true + true + enable + KickStreamHub + LDKickWatch + 1.2.0 + LD KickWatch + LD KickWatch + LD KickWatch + Resources\app.ico + latest + true + AnyCPU + + + + + + + + + + + + diff --git a/src/KickStreamHub/Models/AppConfig.cs b/src/KickStreamHub/Models/AppConfig.cs new file mode 100644 index 0000000..77d10cc --- /dev/null +++ b/src/KickStreamHub/Models/AppConfig.cs @@ -0,0 +1,39 @@ +using System.Collections.ObjectModel; + +namespace KickStreamHub.Models; + +public class AppConfig +{ + public ObservableCollection Favorites { get; set; } = new() + { + "elwind", "wtcn", "pqueen", "unlostv", "kendinemuzisyen" + }; + + public Dictionary 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; +} diff --git a/src/KickStreamHub/Models/ChannelStatus.cs b/src/KickStreamHub/Models/ChannelStatus.cs new file mode 100644 index 0000000..a74d996 --- /dev/null +++ b/src/KickStreamHub/Models/ChannelStatus.cs @@ -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; +} diff --git a/src/KickStreamHub/Models/KickApiModels.cs b/src/KickStreamHub/Models/KickApiModels.cs new file mode 100644 index 0000000..e349198 --- /dev/null +++ b/src/KickStreamHub/Models/KickApiModels.cs @@ -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? Categories { get; set; } +} + +public class KickCategory +{ + [JsonPropertyName("name")] + public string? Name { get; set; } +} + +public class KickChatroom +{ + [JsonPropertyName("id")] + public long Id { get; set; } +} diff --git a/src/KickStreamHub/Resources/Styles.xaml b/src/KickStreamHub/Resources/Styles.xaml new file mode 100644 index 0000000..e23fcb1 --- /dev/null +++ b/src/KickStreamHub/Resources/Styles.xaml @@ -0,0 +1,384 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/KickStreamHub/Resources/app.ico b/src/KickStreamHub/Resources/app.ico new file mode 100644 index 0000000..875d745 Binary files /dev/null and b/src/KickStreamHub/Resources/app.ico differ diff --git a/src/KickStreamHub/Services/AvatarCacheService.cs b/src/KickStreamHub/Services/AvatarCacheService.cs new file mode 100644 index 0000000..ff74974 --- /dev/null +++ b/src/KickStreamHub/Services/AvatarCacheService.cs @@ -0,0 +1,81 @@ +using System.IO; + +namespace KickStreamHub.Services; + +/// +/// 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. +/// +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 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 activeChannels) + { + try + { + var activeSet = new HashSet(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}"); + } + } +} diff --git a/src/KickStreamHub/Services/ConfigService.cs b/src/KickStreamHub/Services/ConfigService.cs new file mode 100644 index 0000000..ff1d83a --- /dev/null +++ b/src/KickStreamHub/Services/ConfigService.cs @@ -0,0 +1,75 @@ +using System.IO; +using System.Text.Json; +using KickStreamHub.Models; + +namespace KickStreamHub.Services; + +/// +/// 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. +/// +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(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); + } + } +} diff --git a/src/KickStreamHub/Services/KickApiService.cs b/src/KickStreamHub/Services/KickApiService.cs new file mode 100644 index 0000000..5557279 --- /dev/null +++ b/src/KickStreamHub/Services/KickApiService.cs @@ -0,0 +1,79 @@ +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using KickStreamHub.Models; + +namespace KickStreamHub.Services; + +/// +/// 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. +/// +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 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(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 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; + } + } +} diff --git a/src/KickStreamHub/Services/LiveStatusPollingService.cs b/src/KickStreamHub/Services/LiveStatusPollingService.cs new file mode 100644 index 0000000..3d8266a --- /dev/null +++ b/src/KickStreamHub/Services/LiveStatusPollingService.cs @@ -0,0 +1,127 @@ +using System.Collections.Concurrent; +using KickStreamHub.Models; + +namespace KickStreamHub.Services; + +public class LiveStatusResultEventArgs : EventArgs +{ + public IReadOnlyDictionary Results { get; } + public LiveStatusResultEventArgs(IReadOnlyDictionary results) => Results = results; +} + +/// +/// 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. +/// +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 _channels = Array.Empty(); + + public event EventHandler? ResultsReady; + public event EventHandler? StatusMessage; + + public LiveStatusPollingService(KickApiService api) + { + _api = api; + } + + public void UpdateChannelList(IReadOnlyList 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(); + + 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 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(); + } +} diff --git a/src/KickStreamHub/Services/LoggingService.cs b/src/KickStreamHub/Services/LoggingService.cs new file mode 100644 index 0000000..1626557 --- /dev/null +++ b/src/KickStreamHub/Services/LoggingService.cs @@ -0,0 +1,71 @@ +using System.IO; +using System.Text; + +namespace KickStreamHub.Services; + +public enum LogLevel { Info, Warning, Error } + +/// +/// 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). +/// +public sealed class LoggingService +{ + private static readonly Lazy _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)!; +} diff --git a/src/KickStreamHub/Services/NotificationService.cs b/src/KickStreamHub/Services/NotificationService.cs new file mode 100644 index 0000000..2657609 --- /dev/null +++ b/src/KickStreamHub/Services/NotificationService.cs @@ -0,0 +1,71 @@ +using System.Windows.Forms; +using Application = System.Windows.Application; + +namespace KickStreamHub.Services; + +/// +/// Sistem tepsisi simgesini ve bildirimleri (balloon tip) yönetir. +/// +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 { } + } +} diff --git a/src/KickStreamHub/Services/PusherChatService.cs b/src/KickStreamHub/Services/PusherChatService.cs new file mode 100644 index 0000000..40b8a27 --- /dev/null +++ b/src/KickStreamHub/Services/PusherChatService.cs @@ -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"; +} + +/// +/// 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. +/// +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? MessageReceived; + public event EventHandler? 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(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(bytes), WebSocketMessageType.Text, true, ct) + .ConfigureAwait(false); + } + finally + { + _sendLock.Release(); + } + } + + public async ValueTask DisposeAsync() + { + await DisconnectAsync().ConfigureAwait(false); + _cts?.Dispose(); + _sendLock.Dispose(); + } +} diff --git a/src/KickStreamHub/Services/SoundService.cs b/src/KickStreamHub/Services/SoundService.cs new file mode 100644 index 0000000..17ff68c --- /dev/null +++ b/src/KickStreamHub/Services/SoundService.cs @@ -0,0 +1,82 @@ +using System.IO; +using System.Media; + +namespace KickStreamHub.Services; + +/// +/// 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. +/// +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(); + } +} diff --git a/src/KickStreamHub/Services/StartupService.cs b/src/KickStreamHub/Services/StartupService.cs new file mode 100644 index 0000000..654376c --- /dev/null +++ b/src/KickStreamHub/Services/StartupService.cs @@ -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; + } + } +} diff --git a/src/KickStreamHub/Services/StreamlinkService.cs b/src/KickStreamHub/Services/StreamlinkService.cs new file mode 100644 index 0000000..c9aca0c --- /dev/null +++ b/src/KickStreamHub/Services/StreamlinkService.cs @@ -0,0 +1,288 @@ +using System.Diagnostics; +using System.IO; + +namespace KickStreamHub.Services; + +/// +/// Streamlink + oynatıcı (Pencere İçi VLC, Harici VLC, Harici MPV) işlemlerini bulan, başlatan ve +/// izleyen servis. +/// +public sealed class StreamlinkService +{ + private readonly Dictionary _activeProcesses = new(StringComparer.OrdinalIgnoreCase); + private Process? _embeddedVlcProcess; + private string? _embeddedVlcChannel; + private readonly object _lock = new(); + + public event EventHandler? ProcessExited; + + public string? FindStreamlink(string? configuredPath) + { + if (!string.IsNullOrWhiteSpace(configuredPath) && File.Exists(configuredPath)) + return configuredPath; + + var candidates = new List + { + "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; + } + } + + /// + /// 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. + /// + 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(); + } + } +} diff --git a/src/KickStreamHub/ViewModels/ChannelCardViewModel.cs b/src/KickStreamHub/ViewModels/ChannelCardViewModel.cs new file mode 100644 index 0000000..101ff07 --- /dev/null +++ b/src/KickStreamHub/ViewModels/ChannelCardViewModel.cs @@ -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"; +} diff --git a/src/KickStreamHub/ViewModels/ChatViewModel.cs b/src/KickStreamHub/ViewModels/ChatViewModel.cs new file mode 100644 index 0000000..b98ace7 --- /dev/null +++ b/src/KickStreamHub/ViewModels/ChatViewModel.cs @@ -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 Messages { get; } = new(); + public ObservableCollection 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(); + } +} diff --git a/src/KickStreamHub/ViewModels/MainViewModel.cs b/src/KickStreamHub/ViewModels/MainViewModel.cs new file mode 100644 index 0000000..14ef12d --- /dev/null +++ b/src/KickStreamHub/ViewModels/MainViewModel.cs @@ -0,0 +1,1193 @@ +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Windows; +using System.Windows.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using KickStreamHub.Models; +using KickStreamHub.Services; +using KickStreamHub.Views; + +namespace KickStreamHub.ViewModels; + +public class MultiSlotPlayEventArgs : EventArgs +{ + public int SlotIndex { get; init; } + public string ChannelName { get; init; } = string.Empty; + public bool IsMuted { get; init; } +} + +public partial class MainViewModel : ObservableObject +{ + private const string AllGroupsLabel = "Tüm Gruplar"; + + private readonly ConfigService _configService; + private readonly KickApiService _api; + private readonly AvatarCacheService _avatarCache; + private readonly LiveStatusPollingService _poller; + public readonly StreamlinkService Streamlink; + public NotificationService? Notifications { get; set; } + + private readonly Dictionary _statusCache = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _notifiedLive = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _notifiedKeywords = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _openChatWindows = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _openPlayerWindows = new(StringComparer.OrdinalIgnoreCase); + private readonly Dispatcher _dispatcher; + + public string AppVersion => System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString(3) ?? "1.0.0"; + public string LogDirectoryPath => LoggingService.Instance.LogDirectory; + + public AppConfig Config { get; } + + public ObservableCollection Channels { get; } = new(); + public ObservableCollection GroupFilterOptions { get; } = new() { AllGroupsLabel }; + public ObservableCollection MultiSlots { get; } = new(); + + // Embedded (Split-View) Chat ViewModel + public ChatViewModel EmbeddedChat { get; } = new(); + + [ObservableProperty] private string _statusMessage = "Hazır."; + [ObservableProperty] private string _searchText = string.Empty; + [ObservableProperty] private bool _onlyLiveFilter; + [ObservableProperty] private string _selectedGroupFilter = AllGroupsLabel; + [ObservableProperty] private int _visibleChannelCount; + [ObservableProperty] private ChannelCardViewModel? _selectedChannel; + [ObservableProperty] private string _addChannelText = string.Empty; + [ObservableProperty] private string _addChannelGroupText = string.Empty; + [ObservableProperty] private string _bulkImportText = string.Empty; + [ObservableProperty] private string _activePage = "home"; + [ObservableProperty] private int _totalChannels; + [ObservableProperty] private int _liveCount; + [ObservableProperty] private long _totalViewers; + [ObservableProperty] private bool _isRefreshing; + + // Detail panel & Embedded Player bindings + [ObservableProperty] private bool _hasSelectedChannel; + [ObservableProperty] private string _detailName = "KANAL SEÇİN"; + [ObservableProperty] private string _detailTitle = "Listeden bir yayıncı seçin."; + [ObservableProperty] private string _detailCategory = string.Empty; + [ObservableProperty] private string _detailViewers = string.Empty; + [ObservableProperty] private string _detailGroupInput = string.Empty; + [ObservableProperty] private bool _detailIsLive; + [ObservableProperty] private bool _detailVerified; + [ObservableProperty] private string? _detailAvatarPath; + [ObservableProperty] private bool _detailIsPlaying; + + [ObservableProperty] private bool _isEmbeddedPlaying; + [ObservableProperty] private bool _isEmbeddedVlcActive; + [ObservableProperty] private bool _isEmbeddedWebActive; + [ObservableProperty] private bool _isEmbeddedMuted; + [ObservableProperty] private bool _isTheaterMode; + [ObservableProperty] private bool _isFullScreen; + [ObservableProperty] private bool _isEmbeddedChatOpen; + [ObservableProperty] private string _activePlayerChannel = string.Empty; + + // Multi-Stream (Squad View) bindings + [ObservableProperty] private bool _isQuadLayout = true; + + public event EventHandler? EmbeddedPlayRequested; + public event EventHandler? EmbeddedVlcPlayRequested; + public event EventHandler? EmbeddedStopRequested; + public event EventHandler? EmbeddedMuteRequested; + public event EventHandler? EmbeddedReloadRequested; + public event EventHandler? FullScreenChanged; + + public event EventHandler? MultiSlotPlayRequested; + public event EventHandler? MultiSlotStopRequested; + public event EventHandler? MultiSlotMuteRequested; + + public MainViewModel() + { + _dispatcher = Dispatcher.CurrentDispatcher; + _configService = new ConfigService(); + Config = _configService.Load(); + Config.RunOnStartup = StartupService.IsRunOnStartup(); + _isEmbeddedChatOpen = Config.ShowEmbeddedChat; + + _api = new KickApiService(); + _avatarCache = new AvatarCacheService(_configService.AvatarCacheDirectory, _api); + Streamlink = new StreamlinkService(); + Streamlink.ProcessExited += (_, _) => _dispatcher.BeginInvoke(() => + { + if (IsEmbeddedVlcActive && !Streamlink.IsPlaying(ActivePlayerChannel)) + { + IsEmbeddedPlaying = false; + IsEmbeddedVlcActive = false; + IsEmbeddedWebActive = false; + ActivePlayerChannel = string.Empty; + } + UpdateDetailPlayState(); + }); + + _poller = new LiveStatusPollingService(_api); + _poller.ResultsReady += OnResultsReady; + _poller.StatusMessage += (_, msg) => _dispatcher.BeginInvoke(() => StatusMessage = msg); + + for (int i = 0; i < 4; i++) + { + MultiSlots.Add(new MultiStreamSlotViewModel { SlotIndex = i, IsMuted = i != 0 }); + } + + foreach (var fav in Config.Favorites) + { + Config.ChannelGroups.TryGetValue(fav, out var grp); + var card = new ChannelCardViewModel(fav, grp ?? string.Empty); + if (_avatarCache.TryGetFreshCachedPath(fav, out var cachedAvatar)) + card.AvatarPath = cachedAvatar; + Channels.Add(card); + } + + RebuildGroupFilterOptions(); + TotalChannels = Channels.Count; + VisibleChannelCount = Channels.Count; + _poller.UpdateChannelList(Config.Favorites.ToList()); + + if (Channels.Count > 0) + SelectedChannel = Channels[0]; + } + + public void Start() + { + _poller.Start(Math.Max(20, Config.RefreshIntervalSeconds)); + _avatarCache.CleanupStale(Config.Favorites); + LoggingService.Instance.Info("LD KickWatch başlatıldı."); + } + + public void Stop() + { + _poller.Stop(); + StopEmbeddedPlayer(); + Streamlink.StopAll(); + _ = EmbeddedChat.DisposeAsync(); + + foreach (var win in _openChatWindows.Values.ToList()) + { + try { win.Close(); } catch { } + } + foreach (var win in _openPlayerWindows.Values.ToList()) + { + try { win.Close(); } catch { } + } + + Config.ShowEmbeddedChat = IsEmbeddedChatOpen; + _configService.Save(Config); + } + + public void SaveConfig() + { + Config.ShowEmbeddedChat = IsEmbeddedChatOpen; + _configService.Save(Config); + StartupService.SetRunOnStartup(Config.RunOnStartup); + _poller.Start(Math.Max(20, Config.RefreshIntervalSeconds)); + UpdateDetailPlayState(); + } + + [RelayCommand] + private async Task RefreshAsync() + { + if (IsRefreshing) return; + IsRefreshing = true; + try + { + await _poller.RefreshNowAsync(); + } + finally + { + IsRefreshing = false; + } + } + + [RelayCommand] + private void AddChannel() + { + var raw = AddChannelText.Trim(); + if (string.IsNullOrWhiteSpace(raw)) return; + + var urlMatch = Regex.Match(raw, @"kick\.com/([a-zA-Z0-9_-]+)", RegexOptions.IgnoreCase); + var name = (urlMatch.Success ? urlMatch.Groups[1].Value : raw.TrimStart('@').Trim('/')).ToLowerInvariant(); + + if (!Regex.IsMatch(name, "^[a-z0-9_-]{2,30}$")) + { + StatusMessage = "⚠ Geçersiz kanal adı. Yalnızca harf, rakam, tire ve alt çizgi kullanılabilir."; + return; + } + if (Config.Favorites.Any(f => f.Equals(name, StringComparison.OrdinalIgnoreCase))) + { + StatusMessage = $"ℹ '{name}' kanalı zaten takip listenizde."; + return; + } + + var grp = AddChannelGroupText.Trim(); + Config.Favorites.Add(name); + if (!string.IsNullOrWhiteSpace(grp)) + Config.ChannelGroups[name] = grp; + + var newCard = new ChannelCardViewModel(name, grp); + if (_avatarCache.TryGetFreshCachedPath(name, out var cachedAvatar)) + newCard.AvatarPath = cachedAvatar; + + Channels.Add(newCard); + SelectedChannel = newCard; + AddChannelText = string.Empty; + + RebuildGroupFilterOptions(); + ApplyFilter(); + UpdateStats(); + _poller.UpdateChannelList(Config.Favorites.ToList()); + _configService.Save(Config); + StatusMessage = $"✔ '{name}' kanalı eklendi, durum sorgulanıyor..."; + _ = _poller.RefreshNowAsync(); + } + + [RelayCommand] + private void SaveChannelGroup() + { + if (SelectedChannel is null) return; + var grp = DetailGroupInput.Trim(); + SelectedChannel.GroupName = grp; + + if (string.IsNullOrWhiteSpace(grp)) + Config.ChannelGroups.Remove(SelectedChannel.ChannelName); + else + Config.ChannelGroups[SelectedChannel.ChannelName] = grp; + + RebuildGroupFilterOptions(); + ApplyFilter(); + _configService.Save(Config); + StatusMessage = string.IsNullOrWhiteSpace(grp) + ? $"🏷 '{SelectedChannel.ChannelName}' grup etiketi kaldırıldı." + : $"🏷 '{SelectedChannel.ChannelName}' kanalı '{grp}' grubuna atandı."; + } + + private void RebuildGroupFilterOptions() + { + var current = SelectedGroupFilter; + var groups = Channels + .Select(c => c.GroupName) + .Where(g => !string.IsNullOrWhiteSpace(g)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(g => g) + .ToList(); + + GroupFilterOptions.Clear(); + GroupFilterOptions.Add(AllGroupsLabel); + foreach (var g in groups) + GroupFilterOptions.Add(g); + + SelectedGroupFilter = GroupFilterOptions.Contains(current) ? current : AllGroupsLabel; + } + + [RelayCommand] + private void RemoveChannel(string? channelName) + { + channelName ??= SelectedChannel?.ChannelName; + if (string.IsNullOrEmpty(channelName)) return; + + if (IsEmbeddedPlaying && string.Equals(ActivePlayerChannel, channelName, StringComparison.OrdinalIgnoreCase)) + StopEmbeddedPlayer(); + + Streamlink.Stop(channelName); + + var card = Channels.FirstOrDefault(c => c.ChannelName.Equals(channelName, StringComparison.OrdinalIgnoreCase)); + if (card != null) Channels.Remove(card); + + var fav = Config.Favorites.FirstOrDefault(f => f.Equals(channelName, StringComparison.OrdinalIgnoreCase)); + if (fav != null) Config.Favorites.Remove(fav); + + Config.ChannelGroups.Remove(channelName); + _statusCache.Remove(channelName); + _notifiedLive.Remove(channelName); + + RebuildGroupFilterOptions(); + ApplyFilter(); + UpdateStats(); + _poller.UpdateChannelList(Config.Favorites.ToList()); + _configService.Save(Config); + + if (SelectedChannel is null || SelectedChannel.ChannelName.Equals(channelName, StringComparison.OrdinalIgnoreCase)) + { + SelectedChannel = Channels.FirstOrDefault(c => c.IsVisible) ?? Channels.FirstOrDefault(); + if (SelectedChannel is null) + ResetDetailPanel(); + } + + StatusMessage = $"🗑 '{channelName}' listeden kaldırıldı."; + } + + [RelayCommand] + private void PlayChannel(string? channelName) + { + channelName ??= SelectedChannel?.ChannelName; + if (string.IsNullOrEmpty(channelName)) return; + + var targetCard = Channels.FirstOrDefault(c => c.ChannelName.Equals(channelName, StringComparison.OrdinalIgnoreCase)); + if (targetCard != null) + SelectedChannel = targetCard; + + // 1. Pencere İçi Web Oynatıcı (WebView2) + if (string.Equals(Config.PlayerChoice, "embedded", StringComparison.OrdinalIgnoreCase)) + { + if (IsEmbeddedPlaying && IsEmbeddedWebActive && string.Equals(ActivePlayerChannel, channelName, StringComparison.OrdinalIgnoreCase)) + { + StopEmbeddedPlayer(); + StatusMessage = "⏹ Dahili yayın durduruldu."; + } + else + { + PlayEmbeddedWebPlayer(channelName); + StatusMessage = $"▶ {channelName.ToUpperInvariant()} yayını Web oynatıcıda açıldı."; + } + UpdateDetailPlayState(); + return; + } + + // 2. Pencere İçi VLC Oynatıcı (Embedded VLC) + if (string.Equals(Config.PlayerChoice, "embedded_vlc", StringComparison.OrdinalIgnoreCase)) + { + if (IsEmbeddedPlaying && IsEmbeddedVlcActive && string.Equals(ActivePlayerChannel, channelName, StringComparison.OrdinalIgnoreCase)) + { + StopEmbeddedPlayer(); + StatusMessage = "⏹ Pencere içi VLC yayını durduruldu."; + } + else + { + PlayEmbeddedVlcPlayer(channelName); + } + UpdateDetailPlayState(); + return; + } + + // 3. Harici VLC veya MPV Oynatıcı + var streamlinkPath = Streamlink.FindStreamlink(Config.StreamlinkPath); + var playerPath = Streamlink.FindPlayer(Config.PlayerChoice, Config.PlayerPath); + if (streamlinkPath is null) + { + StatusMessage = "⚠ Streamlink bulunamadı! Ayarlardan 'Dahili Web' veya 'Pencere İçi VLC' seçebilir ya da Streamlink kurabilirsiniz."; + return; + } + if (playerPath is null) + { + StatusMessage = $"⚠ {Config.PlayerChoice.ToUpperInvariant()} bulunamadı! Ayarlardan oynatıcı tercihini değiştirin veya yolu belirtin."; + return; + } + + var (success, message) = Streamlink.Play(channelName, streamlinkPath, playerPath, Config.StreamQuality, Config.ExtraStreamlinkArgs); + StatusMessage = message; + + if (success && Config.AutoOpenChat && Streamlink.IsPlaying(channelName)) + OpenChat(channelName); + + UpdateDetailPlayState(); + } + + public void PlayEmbeddedWebPlayer(string channelName) + { + Streamlink.StopEmbeddedVlc(); + ActivePlayerChannel = channelName; + IsEmbeddedVlcActive = false; + IsEmbeddedWebActive = true; + IsEmbeddedPlaying = true; + IsEmbeddedMuted = false; + EmbeddedPlayRequested?.Invoke(this, channelName); + + if (IsEmbeddedChatOpen) + SyncEmbeddedChat(channelName); + else if (Config.AutoOpenChat) + OpenChat(channelName); + } + + public void PlayEmbeddedVlcPlayer(string channelName) + { + var vlcPath = Streamlink.FindPlayer("vlc", Config.PlayerPath); + if (vlcPath is null) + { + StatusMessage = "⚠ VLC Media Player bulunamadı! Pencere içi VLC için VLC kurun veya 'Web Oynatıcı' moduna geçin."; + return; + } + + EmbeddedStopRequested?.Invoke(this, EventArgs.Empty); + ActivePlayerChannel = channelName; + IsEmbeddedWebActive = false; + IsEmbeddedVlcActive = true; + IsEmbeddedPlaying = true; + EmbeddedVlcPlayRequested?.Invoke(this, channelName); + + if (IsEmbeddedChatOpen) + SyncEmbeddedChat(channelName); + else if (Config.AutoOpenChat) + OpenChat(channelName); + } + + [RelayCommand] + private void SwitchEmbeddedEngine(string engine) + { + if (string.IsNullOrWhiteSpace(engine)) return; + Config.PlayerChoice = engine; + _configService.Save(Config); + + var targetChannel = !string.IsNullOrEmpty(ActivePlayerChannel) + ? ActivePlayerChannel + : SelectedChannel?.ChannelName; + + if (!string.IsNullOrEmpty(targetChannel) && IsEmbeddedPlaying) + { + if (engine.Equals("embedded_vlc", StringComparison.OrdinalIgnoreCase)) + PlayEmbeddedVlcPlayer(targetChannel); + else + PlayEmbeddedWebPlayer(targetChannel); + + UpdateDetailPlayState(); + } + } + + [RelayCommand] + private void ReloadEmbeddedPlayer() + { + if (!IsEmbeddedPlaying || string.IsNullOrEmpty(ActivePlayerChannel)) return; + if (IsEmbeddedVlcActive) + { + PlayEmbeddedVlcPlayer(ActivePlayerChannel); + } + else + { + EmbeddedReloadRequested?.Invoke(this, EventArgs.Empty); + StatusMessage = $"⟳ {ActivePlayerChannel.ToUpperInvariant()} oynatıcısı yenilendi."; + } + } + + [RelayCommand] + private void ToggleEmbeddedMute() + { + if (!IsEmbeddedWebActive) return; + IsEmbeddedMuted = !IsEmbeddedMuted; + EmbeddedMuteRequested?.Invoke(this, IsEmbeddedMuted); + } + + [RelayCommand] + private void StopEmbedded() + { + StopEmbeddedPlayer(); + UpdateDetailPlayState(); + StatusMessage = "⏹ Yayın oynatıcı kapatıldı."; + } + + [RelayCommand] + private void ToggleTheaterMode() + { + IsTheaterMode = !IsTheaterMode; + if (!IsTheaterMode && IsFullScreen) + { + SetFullScreenState(false); + } + } + + [RelayCommand] + private void ToggleFullScreen() + { + SetFullScreenState(!IsFullScreen); + } + + public void SetFullScreenState(bool enable) + { + if (IsFullScreen == enable) return; + IsFullScreen = enable; + if (enable) + { + IsTheaterMode = true; + } + FullScreenChanged?.Invoke(this, enable); + } + + [RelayCommand] + private void ToggleEmbeddedChat() + { + IsEmbeddedChatOpen = !IsEmbeddedChatOpen; + Config.ShowEmbeddedChat = IsEmbeddedChatOpen; + if (IsEmbeddedChatOpen) + { + var ch = !string.IsNullOrEmpty(ActivePlayerChannel) ? ActivePlayerChannel : SelectedChannel?.ChannelName; + if (!string.IsNullOrEmpty(ch)) + SyncEmbeddedChat(ch); + } + else + { + _ = EmbeddedChat.DisconnectAsync(); + } + } + + private void SyncEmbeddedChat(string channelName) + { + if (!IsEmbeddedChatOpen || string.IsNullOrWhiteSpace(channelName)) return; + var status = GetStatus(channelName); + var chatroomId = status?.ChatroomId ?? 0; + if (chatroomId > 0) + { + _ = EmbeddedChat.ConnectAsync(channelName, chatroomId); + } + else + { + EmbeddedChat.ChannelName = channelName; + } + } + + // ==================== MULTI-STREAM (SQUAD VIEW) COMMANDS ==================== + + [RelayCommand] + private void SendToMultiStream(string? channelName) + { + channelName ??= SelectedChannel?.ChannelName; + if (string.IsNullOrWhiteSpace(channelName)) return; + + var existingSlot = MultiSlots.FirstOrDefault(s => s.IsActive && s.ChannelName.Equals(channelName, StringComparison.OrdinalIgnoreCase)); + if (existingSlot is null) + { + var targetSlot = MultiSlots.FirstOrDefault(s => !s.IsActive) ?? MultiSlots[0]; + targetSlot.ChannelName = channelName; + StartMultiSlot(targetSlot); + } + + ActivePage = "multistream"; + StatusMessage = $"⊞ '{channelName}' çoklu yayın ekranına eklendi."; + } + + [RelayCommand] + private void AutoFillLiveToMultiStream() + { + var liveChannels = Channels.Where(c => c.IsLive).Select(c => c.ChannelName).Take(4).ToList(); + if (liveChannels.Count == 0) + { + liveChannels = Channels.Select(c => c.ChannelName).Take(4).ToList(); + } + + for (int i = 0; i < MultiSlots.Count; i++) + { + if (i < liveChannels.Count) + { + MultiSlots[i].ChannelName = liveChannels[i]; + MultiSlots[i].IsMuted = i != 0; + StartMultiSlot(MultiSlots[i]); + } + } + StatusMessage = $"⊞ {liveChannels.Count} kanal çoklu yayın ızgarasına yerleştirildi."; + } + + [RelayCommand] + private void StartMultiSlot(MultiStreamSlotViewModel? slot) + { + if (slot is null || string.IsNullOrWhiteSpace(slot.ChannelName)) return; + var clean = slot.ChannelName.Trim().TrimStart('@').ToLowerInvariant(); + slot.ChannelName = clean; + slot.IsActive = true; + MultiSlotPlayRequested?.Invoke(this, new MultiSlotPlayEventArgs + { + SlotIndex = slot.SlotIndex, + ChannelName = clean, + IsMuted = slot.IsMuted, + }); + } + + [RelayCommand] + private void StopMultiSlot(MultiStreamSlotViewModel? slot) + { + if (slot is null) return; + slot.IsActive = false; + MultiSlotStopRequested?.Invoke(this, slot.SlotIndex); + } + + [RelayCommand] + private void SoloAudioMultiSlot(MultiStreamSlotViewModel? targetSlot) + { + if (targetSlot is null) return; + foreach (var s in MultiSlots) + { + s.IsMuted = s.SlotIndex != targetSlot.SlotIndex; + if (s.IsActive) + { + MultiSlotMuteRequested?.Invoke(this, new MultiSlotPlayEventArgs + { + SlotIndex = s.SlotIndex, + ChannelName = s.ChannelName, + IsMuted = s.IsMuted, + }); + } + } + StatusMessage = $"🔊 Yalnızca #{targetSlot.SlotIndex + 1} ({targetSlot.ChannelName}) sesi aktif edildi."; + } + + [RelayCommand] + private void ToggleMultiLayout() + { + IsQuadLayout = !IsQuadLayout; + } + + [RelayCommand] + private void StopAllMultiStream() + { + foreach (var s in MultiSlots) + { + s.IsActive = false; + MultiSlotStopRequested?.Invoke(this, s.SlotIndex); + } + StatusMessage = "⏹ Tüm çoklu yayın ekranları kapatıldı."; + } + + // ==================== POPOUT & CHAT COMMANDS ==================== + + [RelayCommand] + private void PlayPopout(string? channelName) + { + channelName ??= SelectedChannel?.ChannelName; + if (string.IsNullOrEmpty(channelName)) return; + + if (IsEmbeddedPlaying && string.Equals(ActivePlayerChannel, channelName, StringComparison.OrdinalIgnoreCase)) + { + StopEmbeddedPlayer(); + UpdateDetailPlayState(); + } + + if (_openPlayerWindows.TryGetValue(channelName, out var existingWin) && existingWin.IsLoaded) + { + if (existingWin.WindowState == WindowState.Minimized) + existingWin.WindowState = WindowState.Normal; + existingWin.Activate(); + return; + } + + var popout = new PlayerWindow(channelName); + _openPlayerWindows[channelName] = popout; + popout.Closed += (_, _) => _openPlayerWindows.Remove(channelName); + popout.Show(); + StatusMessage = $"⛶ {channelName.ToUpperInvariant()} ayrı pencerede açıldı."; + } + + public void StopEmbeddedPlayer() + { + if (IsFullScreen) + SetFullScreenState(false); + + Streamlink.StopEmbeddedVlc(); + IsEmbeddedPlaying = false; + IsEmbeddedVlcActive = false; + IsEmbeddedWebActive = false; + IsTheaterMode = false; + ActivePlayerChannel = string.Empty; + EmbeddedStopRequested?.Invoke(this, EventArgs.Empty); + } + + [RelayCommand] + private async Task OpenChatAsync(string? channelName) + { + OpenChat(channelName); + await Task.CompletedTask; + } + + private void OpenChat(string? channelName) + { + channelName ??= SelectedChannel?.ChannelName; + if (string.IsNullOrEmpty(channelName)) return; + + if (_openChatWindows.TryGetValue(channelName, out var existingChat) && existingChat.IsLoaded) + { + if (existingChat.WindowState == WindowState.Minimized) + existingChat.WindowState = WindowState.Normal; + existingChat.Activate(); + return; + } + + var status = GetStatus(channelName); + var chatroomId = status?.ChatroomId ?? 0; + if (chatroomId == 0) + { + StatusMessage = "⏳ Sohbet odası bilgisi henüz yüklenmedi, lütfen birkaç saniye bekleyin."; + return; + } + + var chatWindow = new ChatWindow(channelName, chatroomId, Config.ChatMaxMessages); + _openChatWindows[channelName] = chatWindow; + chatWindow.Closed += (_, _) => _openChatWindows.Remove(channelName); + chatWindow.Show(); + } + + [RelayCommand] + private void OpenInBrowser(string? channelName) + { + channelName ??= SelectedChannel?.ChannelName; + if (string.IsNullOrEmpty(channelName)) return; + try + { + Process.Start(new ProcessStartInfo($"https://kick.com/{channelName}") { UseShellExecute = true }); + } + catch (Exception ex) + { + StatusMessage = $"Tarayıcı açılamadı: {ex.Message}"; + } + } + + [RelayCommand] + private void NavigateTo(string page) + { + if (IsFullScreen && page != "home") + SetFullScreenState(false); + ActivePage = page; + } + + [RelayCommand] + private void OpenLogs() + { + try + { + Process.Start(new ProcessStartInfo(LoggingService.Instance.LogDirectory) { UseShellExecute = true }); + } + catch (Exception ex) + { + StatusMessage = $"Log klasörü açılamadı: {ex.Message}"; + } + } + + [RelayCommand] + private void TestNotificationSound() + { + SoundService.PlayNotification(Config.CustomSoundPath, false); + Notifications?.ShowBalloon("🔔 LD KickWatch Bildirim Testi", "Sesli ve görsel bildirimler sorunsuz çalışıyor!"); + StatusMessage = "🔊 Bildirim sesi test edildi."; + } + + // ==================== IMPORT / EXPORT FAVORITES ==================== + + public void ExportFavoritesToFile(string filePath) + { + try + { + if (filePath.EndsWith(".csv", StringComparison.OrdinalIgnoreCase)) + { + var sb = new StringBuilder(); + sb.AppendLine("ChannelName,GroupName"); + foreach (var ch in Config.Favorites) + { + Config.ChannelGroups.TryGetValue(ch, out var grp); + sb.AppendLine($"{ch},{grp ?? string.Empty}"); + } + File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8); + } + else + { + var exportObj = new + { + ExportedAt = DateTime.Now, + Favorites = Config.Favorites, + ChannelGroups = Config.ChannelGroups, + }; + var json = JsonSerializer.Serialize(exportObj, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(filePath, json, Encoding.UTF8); + } + StatusMessage = $"📤 {Config.Favorites.Count} kanal başarıyla dışa aktarıldı: {Path.GetFileName(filePath)}"; + } + catch (Exception ex) + { + StatusMessage = $"⚠ Dışa aktarma hatası: {ex.Message}"; + } + } + + public void ImportFavoritesFromFile(string filePath) + { + try + { + int added = 0; + if (filePath.EndsWith(".csv", StringComparison.OrdinalIgnoreCase)) + { + var lines = File.ReadAllLines(filePath, Encoding.UTF8); + foreach (var line in lines.Skip(1)) + { + var parts = line.Split(',', 2); + if (parts.Length == 0) continue; + var name = parts[0].Trim().ToLowerInvariant(); + var grp = parts.Length > 1 ? parts[1].Trim() : string.Empty; + if (TryAddImportedChannel(name, grp)) added++; + } + } + else + { + var json = File.ReadAllText(filePath, Encoding.UTF8); + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + + var groupsDict = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (root.TryGetProperty("ChannelGroups", out var grpEl) && grpEl.ValueKind == JsonValueKind.Object) + { + foreach (var prop in grpEl.EnumerateObject()) + groupsDict[prop.Name] = prop.Value.GetString() ?? string.Empty; + } + + if (root.TryGetProperty("Favorites", out var favEl) && favEl.ValueKind == JsonValueKind.Array) + { + foreach (var item in favEl.EnumerateArray()) + { + var name = item.GetString()?.Trim().ToLowerInvariant(); + if (!string.IsNullOrEmpty(name)) + { + groupsDict.TryGetValue(name, out var g); + if (TryAddImportedChannel(name, g ?? string.Empty)) added++; + } + } + } + } + + FinalizeImport(added); + } + catch (Exception ex) + { + StatusMessage = $"⚠ İçe aktarma hatası: {ex.Message}"; + } + } + + [RelayCommand] + private void BulkImportChannels() + { + if (string.IsNullOrWhiteSpace(BulkImportText)) return; + + var tokens = BulkImportText.Split(new[] { ',', ';', '\r', '\n', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + int added = 0; + var grp = AddChannelGroupText.Trim(); + + foreach (var raw in tokens) + { + var urlMatch = Regex.Match(raw, @"kick\.com/([a-zA-Z0-9_-]+)", RegexOptions.IgnoreCase); + var name = (urlMatch.Success ? urlMatch.Groups[1].Value : raw.TrimStart('@').Trim('/')).ToLowerInvariant(); + if (TryAddImportedChannel(name, grp)) + added++; + } + + BulkImportText = string.Empty; + FinalizeImport(added); + } + + private bool TryAddImportedChannel(string name, string groupName) + { + if (!Regex.IsMatch(name, "^[a-z0-9_-]{2,30}$")) return false; + if (Config.Favorites.Any(f => f.Equals(name, StringComparison.OrdinalIgnoreCase))) + { + if (!string.IsNullOrWhiteSpace(groupName)) + { + Config.ChannelGroups[name] = groupName; + var existing = Channels.FirstOrDefault(c => c.ChannelName.Equals(name, StringComparison.OrdinalIgnoreCase)); + if (existing != null) existing.GroupName = groupName; + } + return false; + } + + Config.Favorites.Add(name); + if (!string.IsNullOrWhiteSpace(groupName)) + Config.ChannelGroups[name] = groupName; + + var card = new ChannelCardViewModel(name, groupName); + if (_avatarCache.TryGetFreshCachedPath(name, out var cached)) + card.AvatarPath = cached; + Channels.Add(card); + return true; + } + + private void FinalizeImport(int addedCount) + { + RebuildGroupFilterOptions(); + ApplyFilter(); + UpdateStats(); + _poller.UpdateChannelList(Config.Favorites.ToList()); + _configService.Save(Config); + StatusMessage = $"📥 {addedCount} yeni kanal başarıyla içe aktarıldı."; + if (addedCount > 0) + _ = _poller.RefreshNowAsync(); + } + + // ==================== FILTER & SELECTION LOGIC ==================== + + partial void OnSelectedChannelChanged(ChannelCardViewModel? value) + { + if (value is null) + { + ResetDetailPanel(); + return; + } + HasSelectedChannel = true; + DetailGroupInput = value.GroupName; + UpdateDetailPanel(value.ChannelName); + + if (IsEmbeddedChatOpen && !IsEmbeddedPlaying) + SyncEmbeddedChat(value.ChannelName); + } + + partial void OnSearchTextChanged(string value) => ApplyFilter(); + + partial void OnOnlyLiveFilterChanged(bool value) => ApplyFilter(); + + partial void OnSelectedGroupFilterChanged(string value) => ApplyFilter(); + + private void ApplyFilter() + { + var q = SearchText.Trim(); + var grp = SelectedGroupFilter; + bool filterByGroup = !string.IsNullOrWhiteSpace(grp) && !grp.Equals(AllGroupsLabel, StringComparison.OrdinalIgnoreCase); + + int count = 0; + foreach (var card in Channels) + { + bool matchesSearch = string.IsNullOrEmpty(q) || + card.ChannelName.Contains(q, StringComparison.OrdinalIgnoreCase) || + card.Category.Contains(q, StringComparison.OrdinalIgnoreCase) || + card.Title.Contains(q, StringComparison.OrdinalIgnoreCase) || + card.GroupName.Contains(q, StringComparison.OrdinalIgnoreCase); + bool matchesLive = !OnlyLiveFilter || card.IsLive; + bool matchesGroup = !filterByGroup || card.GroupName.Equals(grp, StringComparison.OrdinalIgnoreCase); + + card.IsVisible = matchesSearch && matchesLive && matchesGroup; + if (card.IsVisible) count++; + } + VisibleChannelCount = count; + } + + private void ResetDetailPanel() + { + HasSelectedChannel = false; + DetailName = "KANAL SEÇİN"; + DetailTitle = "Detayları görmek ve yayını başlatmak için sol listeden bir kanal seçin."; + DetailCategory = string.Empty; + DetailViewers = string.Empty; + DetailGroupInput = string.Empty; + DetailIsLive = false; + DetailVerified = false; + DetailAvatarPath = null; + DetailIsPlaying = false; + } + + private void UpdateDetailPanel(string channelName) + { + HasSelectedChannel = true; + DetailName = channelName; + var status = GetStatus(channelName); + if (status is null) + { + DetailTitle = "Kanal bilgileri Kick.com üzerinden alınıyor..."; + DetailCategory = string.Empty; + DetailViewers = string.Empty; + DetailIsLive = false; + DetailVerified = false; + } + else + { + DetailIsLive = status.IsLive; + DetailVerified = status.Verified; + DetailTitle = status.IsLive + ? (string.IsNullOrWhiteSpace(status.Title) ? "Canlı Yayında" : status.Title) + : "Bu kanal şu anda canlı yayında değil."; + DetailCategory = status.Category; + DetailViewers = status.IsLive + ? (status.Viewers >= 1000 ? $"👥 {status.Viewers / 1000.0:0.0}B anlık izleyici" : $"👥 {status.Viewers} anlık izleyici") + : "Çevrimdışı"; + } + + var card = Channels.FirstOrDefault(c => c.ChannelName.Equals(channelName, StringComparison.OrdinalIgnoreCase)); + DetailAvatarPath = card?.AvatarPath; + + UpdateDetailPlayState(); + } + + private void UpdateDetailPlayState() + { + bool isEmbeddedMode = string.Equals(Config.PlayerChoice, "embedded", StringComparison.OrdinalIgnoreCase) || + string.Equals(Config.PlayerChoice, "embedded_vlc", StringComparison.OrdinalIgnoreCase); + + foreach (var card in Channels) + { + card.IsPlaying = isEmbeddedMode + ? (IsEmbeddedPlaying && string.Equals(card.ChannelName, ActivePlayerChannel, StringComparison.OrdinalIgnoreCase)) + : Streamlink.IsPlaying(card.ChannelName); + } + + if (isEmbeddedMode) + { + DetailIsPlaying = IsEmbeddedPlaying && + SelectedChannel is not null && + string.Equals(SelectedChannel.ChannelName, ActivePlayerChannel, StringComparison.OrdinalIgnoreCase); + } + else + { + DetailIsPlaying = SelectedChannel is not null && + Streamlink.IsPlaying(SelectedChannel.ChannelName); + } + } + + private void OnResultsReady(object? sender, LiveStatusResultEventArgs e) + { + _dispatcher.Invoke(() => ApplyResults(e.Results)); + } + + private void ApplyResults(IReadOnlyDictionary results) + { + var keywords = (Config.AlertKeywords ?? string.Empty) + .Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries) + .Select(k => k.Trim()) + .Where(k => k.Length >= 2) + .ToList(); + + foreach (var (channel, status) in results) + { + if (!status.FetchSucceeded) continue; + + var hadPrev = _statusCache.TryGetValue(channel, out var prev); + var wasLive = hadPrev && prev!.IsLive; + + // 1. Yeni Canlı Yayın Bildirimi + Ses + if (status.IsLive && !wasLive && !_notifiedLive.Contains(channel)) + { + if (Config.NotificationsEnabled) + { + Notifications?.ShowBalloon($"🔴 {channel.ToUpperInvariant()} yayına başladı!", + string.IsNullOrWhiteSpace(status.Category) ? status.Title : $"{status.Category} • {status.Title}"); + } + if (Config.SoundNotificationsEnabled) + { + SoundService.PlayNotification(Config.CustomSoundPath, isKeywordOrCategoryAlert: false); + } + _notifiedLive.Add(channel); + } + // 2. Kategori Değişikliği Bildirimi + Ses + else if (status.IsLive && wasLive && Config.NotifyOnCategoryChange && prev != null && + !string.IsNullOrWhiteSpace(prev.Category) && + !string.IsNullOrWhiteSpace(status.Category) && + !prev.Category.Equals(status.Category, StringComparison.OrdinalIgnoreCase)) + { + if (Config.NotificationsEnabled) + { + Notifications?.ShowBalloon($"🎮 {channel.ToUpperInvariant()} kategori değiştirdi!", + $"Yeni Kategori: {status.Category}\n{status.Title}"); + } + if (Config.SoundNotificationsEnabled) + { + SoundService.PlayNotification(Config.CustomSoundPath, isKeywordOrCategoryAlert: true); + } + } + else if (!status.IsLive) + { + _notifiedLive.Remove(channel); + } + + // 3. Başlık / Kategori Anahtar Kelime Uyarısı + Ses + if (status.IsLive && keywords.Count > 0) + { + foreach (var kw in keywords) + { + if (status.Title.Contains(kw, StringComparison.OrdinalIgnoreCase) || + status.Category.Contains(kw, StringComparison.OrdinalIgnoreCase)) + { + var alertKey = $"{channel}:{kw}:{status.Title}"; + if (_notifiedKeywords.Add(alertKey)) + { + if (Config.NotificationsEnabled) + { + Notifications?.ShowBalloon($"🔔 Anahtar Kelime Yakalandı ({kw})", + $"{channel.ToUpperInvariant()}: {status.Title}"); + } + if (Config.SoundNotificationsEnabled) + { + SoundService.PlayNotification(Config.CustomSoundPath, isKeywordOrCategoryAlert: true); + } + } + break; + } + } + } + + _statusCache[channel] = status; + + var card = Channels.FirstOrDefault(c => c.ChannelName.Equals(channel, StringComparison.OrdinalIgnoreCase)); + card?.ApplyStatus(status); + + if (!string.IsNullOrWhiteSpace(status.ProfilePicUrl)) + _ = LoadAvatarAsync(channel, status.ProfilePicUrl, card); + } + + SortChannels(); + ApplyFilter(); + UpdateStats(); + + if (SelectedChannel is null && Channels.Count > 0) + SelectedChannel = Channels[0]; + else if (SelectedChannel is not null) + UpdateDetailPanel(SelectedChannel.ChannelName); + + // Yerleşik sohbet açıksa ve henüz bağlanmamışsa bağla + if (IsEmbeddedChatOpen && !EmbeddedChat.IsConnected) + { + var chatTarget = !string.IsNullOrEmpty(ActivePlayerChannel) ? ActivePlayerChannel : SelectedChannel?.ChannelName; + if (!string.IsNullOrEmpty(chatTarget)) + SyncEmbeddedChat(chatTarget); + } + } + + private void SortChannels() + { + var sorted = Channels + .OrderByDescending(c => c.IsLive) + .ThenByDescending(c => c.Viewers) + .ThenBy(c => c.ChannelName) + .ToList(); + + bool orderChanged = false; + for (int i = 0; i < sorted.Count; i++) + { + if (!ReferenceEquals(Channels[i], sorted[i])) + { + orderChanged = true; + break; + } + } + + if (!orderChanged) return; + + for (int i = 0; i < sorted.Count; i++) + { + var currentIndex = Channels.IndexOf(sorted[i]); + if (currentIndex != i) + Channels.Move(currentIndex, i); + } + } + + private void UpdateStats() + { + TotalChannels = Channels.Count; + LiveCount = _statusCache.Values.Count(s => s.IsLive); + TotalViewers = _statusCache.Values.Where(s => s.IsLive).Sum(s => s.Viewers); + } + + private async Task LoadAvatarAsync(string channel, string url, ChannelCardViewModel? card) + { + if (card is null) return; + if (_avatarCache.TryGetFreshCachedPath(channel, out var cachedPath)) + { + _dispatcher.Invoke(() => + { + card.AvatarPath = cachedPath; + if (SelectedChannel?.ChannelName.Equals(channel, StringComparison.OrdinalIgnoreCase) == true) + DetailAvatarPath = cachedPath; + }); + return; + } + var path = await _avatarCache.DownloadAndCacheAsync(channel, url); + if (path != null) + { + _dispatcher.Invoke(() => + { + card.AvatarPath = path; + if (SelectedChannel?.ChannelName.Equals(channel, StringComparison.OrdinalIgnoreCase) == true) + DetailAvatarPath = path; + }); + } + } + + public ChannelStatus? GetStatus(string channel) => + _statusCache.TryGetValue(channel, out var s) ? s : null; +} diff --git a/src/KickStreamHub/ViewModels/MultiStreamSlotViewModel.cs b/src/KickStreamHub/ViewModels/MultiStreamSlotViewModel.cs new file mode 100644 index 0000000..82417a8 --- /dev/null +++ b/src/KickStreamHub/ViewModels/MultiStreamSlotViewModel.cs @@ -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; +} diff --git a/src/KickStreamHub/Views/ChatWindow.xaml b/src/KickStreamHub/Views/ChatWindow.xaml new file mode 100644 index 0000000..3405edd --- /dev/null +++ b/src/KickStreamHub/Views/ChatWindow.xaml @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +