chore: add bilingual documentation, MIT license, and clean repository for Forgejo
34
.gitignore
vendored
|
|
@ -10,6 +10,7 @@ x86/
|
|||
bld/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
*.log
|
||||
|
||||
## Visual Studio / Rider / VS Code
|
||||
.vs/
|
||||
|
|
@ -27,6 +28,37 @@ bld/
|
|||
*.dmp
|
||||
*.pdb
|
||||
*.xml
|
||||
publish_small/
|
||||
*.dll
|
||||
|
||||
publish_small/
|
||||
publish/
|
||||
|
||||
## Node / Vite / Web
|
||||
node_modules/
|
||||
dist/
|
||||
dist-ssr/
|
||||
*.local
|
||||
|
||||
## Tauri / Rust
|
||||
src-tauri/target/
|
||||
.cargo/
|
||||
releases/
|
||||
|
||||
## Security & Local Server Scripts (NEVER commit)
|
||||
bağlan.bat
|
||||
*baglan*.bat
|
||||
ba*lan.bat
|
||||
publish.ps1
|
||||
publish.bat
|
||||
release.ps1
|
||||
.keys/
|
||||
*.key
|
||||
*.pem
|
||||
*.pfx
|
||||
*.p12
|
||||
*.sig
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
secrets.*
|
||||
config.local.*
|
||||
|
|
|
|||
|
|
@ -1,22 +0,0 @@
|
|||
|
||||
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
|
||||
213
README.md
|
|
@ -1,193 +1,86 @@
|
|||
<div align="center">
|
||||
|
||||
# 🟢 LD KickWatch
|
||||
<img src="public/logo.png" width="96" alt="LD KickWatch Logo" />
|
||||
|
||||
**Kick.com için Modern Masaüstü Canlı Yayın İzleme Stüdyosu ve Sohbet İstemcisi**
|
||||
# LD KickWatch
|
||||
|
||||
[](https://github.com/LilDosto/LD-KickWatch/releases/latest)
|
||||
[-0078D6?style=for-the-badge&logo=windows)](https://github.com/LilDosto/LD-KickWatch)
|
||||
[](https://dotnet.microsoft.com/download/dotnet/8.0)
|
||||
[](./LICENSE)
|
||||
**Kick.com için masaüstü canlı yayın stüdyosu, 2x2 Çoklu Yayın ve canlı sohbet istemcisi • Desktop livestreaming studio, 2x2 Squad View, and live chat client for Kick.com**
|
||||
|
||||
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.
|
||||
[](./LICENSE)
|
||||
[](https://git.ttmadethat.shop/LilDosto/LD-KickWatch/releases/latest)
|
||||
[](https://v2.tauri.app)
|
||||
[](https://git.ttmadethat.shop/LilDosto/LD-KickWatch/releases/latest)
|
||||
|
||||
[📦 **Son Sürümü İndir (v1.8.0 Releases)**](https://github.com/LilDosto/LD-KickWatch/releases/latest) • [🚀 **Özellikler**](#-başlıca-özellikler) • [⌨ **Kısayollar**](#-klavye-kısayolları) • [🛠 **Derleme**](#-kaynak-koddan-derleme)
|
||||
[🇹🇷 Türkçe](#-türkçe) • [🇬🇧 English](#-english) • [📦 Releases](https://git.ttmadethat.shop/LilDosto/LD-KickWatch/releases/latest)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Başlıca Özellikler
|
||||
## 🇹🇷 Türkçe
|
||||
|
||||
### 🎬 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.
|
||||
**LD KickWatch**, favori Kick.com yayıncılarınızı takip etmenizi, canlı yayınları uygulama içi HLS/MPV oynatıcıyla veya 2x2 Çoklu Yayın (Squad View) ekranında izlemenizi ve gerçek zamanlı sohbete katılmanızı sağlayan Tauri v2 tabanlı masaüstü istemcisidir.
|
||||
|
||||
### ⛶ 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.
|
||||
### Özellikler
|
||||
|
||||
### ⊞ 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.
|
||||
- **Tauri v2 & Asenkron Rust Çekirdeği:** Tokio tabanlı arka plan servisleri, tekil örnek (`single-instance`) pencere koruması ve sistem tepsisi desteği.
|
||||
- **Dahili & Harici Yayın Oynatıcıları:** Uygulama içi HLS (`hls.js`) ve entegre MPV görünümü (`MpvViewport`), Rust üzerinden CORS/WAF köprüsü (`hls_pipe`), otomatik oynatma token yenileme ve kalite seçimi (160p–1080p / Oto); ayrıca kuruluysa harici oynatıcı (VLC/MPV) desteği.
|
||||
- **2x2 Çoklu Yayın (Squad View):** Aynı anda 4 canlı yayını 2x2 ızgarada izleme, canlı favori kanalları otomatik yerleştirme ve tek tıkla solo ses odağı.
|
||||
- **Kick Pusher WebSocket Canlı Sohbet:** Sağ çekmece canlı sohbet paneli, Kick emote/rozet render desteği, mesaj gönderme / Kick oturumu ve yukarı kaydırmada otomatik duraklatma.
|
||||
- **Canlı Takip & Bildirimler:** Kanal takip/gruplama, Top TR / Küçük TR yayın keşfi, canlı yayın ve kategori bildirimleri, polifonik çift tonlu zil veya özel `.wav`/`.mp3` ses uyarıları, global kısayollar ve Minisign imzalı OTA güncelleme.
|
||||
|
||||
### 💬 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.
|
||||
### Teknoloji Yığını
|
||||
|
||||
### 🔔 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.
|
||||
- **Masaüstü & Çekirdek:** Tauri v2 (`tauri 2.5`), Rust (`tokio`, `tokio-tungstenite`, `reqwest`, `rodio`, `libloading`, `windows-sys`)
|
||||
- **Arayüz:** React 18, TypeScript, Tailwind CSS, Zustand, Framer Motion, Vite
|
||||
|
||||
### 🏷 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
|
||||
|
||||
---
|
||||
|
||||
## 📥 Kurulum ve Kullanım
|
||||
|
||||
### Seçenek 1: Resmi Windows Kurulum Sihirbazı (Önerilen)
|
||||
1. Releases sayfasından **[`LD-KickWatch-Setup-v1.8.0.exe`](https://github.com/LilDosto/LD-KickWatch/releases/latest)** kurulum sihirbazını indirin.
|
||||
2. Kurulumu çalıştırın:
|
||||
- Masaüstüne otomatik simgeli kısayol oluşturulur.
|
||||
- Başlat Menüsü'ne "LD KickWatch" eklenir.
|
||||
- Windows "Uygulamalar ve Özellikler" (Denetim Masası) listesine kaydedilir ve temiz kaldırma (Uninstaller) desteği sunar.
|
||||
- Yönetici yetkisi (UAC) gerektirmez; saniyeler içinde kurulur.
|
||||
|
||||
### Seçenek 2: Taşınabilir Tek Dosya (Portable)
|
||||
1. [`publish/LDKickWatch.exe`](./publish/LDKickWatch.exe) veya `LD-KickWatch-v1.8.0-win-x64.zip` dosyasını indirin.
|
||||
2. Doğrudan çift tıklayarak çalıştırın (`.NET Runtime` içine gömülüdür).
|
||||
3. İsterseniz uygulama içi **Ayarlar (⚙)** menüsünden **"🖥️ Masaüstü Kısayolu Oluştur"** butonuna basarak tek tıkla masaüstünüze simgeli kısayol ekleyebilirsiniz.
|
||||
|
||||
### Seçenek 2: Kaynak Koddan Derleme
|
||||
Gereksinimler: [.NET 8.0 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) (Windows)
|
||||
**Son Kullanıcı:**
|
||||
1. [Releases](https://git.ttmadethat.shop/LilDosto/LD-KickWatch/releases/latest) sayfasından `LD-KickWatch-Setup-v2.6.12.exe` (veya `LD-KickWatch-2.6.12.msi`) paketini indirip kurun.
|
||||
2. Favori yayıncılarınızı ekleyin; canlı olduklarında bildirim alın ve tek tıkla izleyin (`F5` yenileme, `Escape` panel kapatma).
|
||||
|
||||
**Geliştirici (Kaynaktan Derleme):**
|
||||
```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
|
||||
npm install
|
||||
npm run tauri dev # Geliştirme modunda çalıştır
|
||||
npm run tauri build # Kurulum paketini (.exe / .msi) derle
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⌨ Klavye Kısayolları
|
||||
## 🇬🇧 English
|
||||
|
||||
| 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 |
|
||||
**LD KickWatch** is a Tauri v2 desktop livestreaming studio and live chat client for Kick.com featuring built-in HLS/MPV playback, 2x2 Squad View, real-time Pusher WebSocket chat, and instant stream notifications.
|
||||
|
||||
---
|
||||
### Features
|
||||
|
||||
## 🏗 Proje Mimarisi
|
||||
- **Tauri v2 & Async Rust Core:** Tokio-powered background polling and streaming services, single-instance guard, persistent window state, and system tray integration.
|
||||
- **Built-in & External Playback:** Embedded HLS (`hls.js`) and MPV viewport (`MpvViewport`) with a Rust CORS/WAF proxy bridge (`hls_pipe`), automatic stream token refresh, quality selector (160p–1080p / Auto), and optional external player (VLC/MPV) launch.
|
||||
- **2x2 Squad View:** Watch up to 4 live streams simultaneously in a 2x2 grid with auto-fill for live channels and one-click solo audio focus.
|
||||
- **Live Pusher WebSocket Chat:** Toggleable right-side chat drawer with Kick emote and badge rendering, Kick auth session support, and scroll-up auto-pause.
|
||||
- **Stream Tracking & Alerts:** Channel grouping, TR stream discovery, live/category notifications, built-in dual-tone or custom `.wav`/`.mp3` sound alerts, global shortcuts, and Minisign-verified OTA updates.
|
||||
|
||||
```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
|
||||
### Tech Stack
|
||||
|
||||
- **Desktop & Backend:** Tauri v2 (`tauri 2.5`), Rust (`tokio`, `tokio-tungstenite`, `reqwest`, `rodio`, `libloading`, `windows-sys`)
|
||||
- **Frontend:** React 18, TypeScript, Tailwind CSS, Zustand, Framer Motion, Vite
|
||||
|
||||
### Installation & Usage
|
||||
|
||||
**End Users:**
|
||||
1. Download `LD-KickWatch-Setup-v2.6.12.exe` (or `LD-KickWatch-2.6.12.msi`) from [Releases](https://git.ttmadethat.shop/LilDosto/LD-KickWatch/releases/latest) and run the installer.
|
||||
2. Add your favorite Kick.com channels to receive live alerts and watch directly inside the app (`F5` refresh, `Escape` close drawer).
|
||||
|
||||
**Developers (Build from Source):**
|
||||
```powershell
|
||||
npm install
|
||||
npm run tauri dev # Run in development mode
|
||||
npm run tauri build # Build production installers (.exe / .msi)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🆕 Sürüm Geçmişi
|
||||
## 📄 Lisans / License
|
||||
|
||||
### 🟢 v1.8.0 (31 Ekim 2026) - Ayrı Pencere (PiP) Çift Oynatıcı Motoru (Web & VLC) & Kalite Seçimi
|
||||
- **🎬 Bağımsız Pencerede (PlayerWindow) Dahili VLC Motoru:** Ayrı pencere (PiP) oynatıcısına doğrudan **🌐 Web** ve **🎬 VLC** motor değiştirme butonları eklendi. Kullanıcılar ayrı pencerede de ultra düşük gecikmeli, donanımsal VLC deneyimini kullanabilir.
|
||||
- **⚙ Ayrı Pencere Kalite Seçici (ContextMenu):** Ayrı pencere üst çubuğuna açılır kalite menüsü (`best`, `1080p60`, `720p60`, `480p`, `360p`, `160p`, `audio_only`) eklendi. Seçilen kaliteye göre VLC yayını anında güncellenir.
|
||||
- **🎨 Görsel Durum & Renkli Vurgular:** Hangi motorun devrede olduğu yeşil (`🌐 Web`) ve sarı/amber (`🎬 VLC`) parlayan buton vurgularıyla net biçimde gösterilir.
|
||||
- **🛡 Job Object & Çift Tıklama Tam Ekran:** Ayrı pencerede VLC aktifken video alanına çift tıklama ile tam ekran geçişi ve pencere kapatıldığında arka plandaki VLC sürecinin Job Object ile kesin olarak sonlandırılması sağlandı.
|
||||
|
||||
### 🟢 v1.7.0 (29 Ekim 2026) - Resmi Windows Kurulum Sihirbazı & Masaüstü Kısayol Entegrasyonu
|
||||
- **📦 Resmi Windows Setup (.exe) Kurulum Paketi:** LD KickWatch artık normal bir Windows programı gibi tek tıkla kurulabilir (`LD-KickWatch-Setup-v1.7.0.exe`).
|
||||
- Kurulum tamamlandığında Masaüstüne özel simgeli kısayol ekler.
|
||||
- Başlat Menüsü'ne "LD KickWatch" program kaydını ekler.
|
||||
- Denetim Masası / Windows Ayarları "Program Ekle veya Kaldır" listesine resmi kayıt açar ve sorunsuz kaldırıcı (Uninstaller) sunar.
|
||||
- Yönetici (Administrator) izni gerektirmeden kullanıcı profiline anında kurulur.
|
||||
- **🖥️ Uygulama İçi Tek Tıkla Masaüstü Kısayolu Oluşturma:** Taşınabilir (Portable) sürümü kullananlar için Ayarlar (⚙) sekmesine *"Masaüstü Kısayolu Oluştur"* butonu eklendi. Tek tıkla masaüstüne uygulama simgesiyle tam çalışan `.lnk` kısayolu bırakır.
|
||||
- **🛡 Gelişmiş Kurulum Koruması:** Kurulum veya güncelleme esnasında LD KickWatch açık ise otomatik algılayıp güvenli şekilde kapatır ve dosyaları sorunsuz günceller.
|
||||
|
||||
### 🟢 v1.6.0 (28 Ekim 2026) - Büyük Akışkanlık & Sıfır Donma Optimize Yaması
|
||||
- **🚀 Donanımsal 60 FPS Render & Animasyon Motoru:** WPF alt motoruna 60 FPS hedef kare hızı (`DesiredFrameRate = 60`) ve tam donanım hızlandırmalı render optimizasyonu uygulandı.
|
||||
- **✨ Kanal Listesi UI Sanallaştırması (Smooth 60 FPS Scrolling):** Takip edilen yayıncılar listesinde donanımsal `VirtualizingStackPanel` ve `Recycling` modu etkinleştirildi. 100+ kanal eklendiğinde dahi sıfır takılma ile kaydırma sağlandı.
|
||||
- **🖼 Bellek İçi Dondurulmuş Avatar Önbelleği (In-Memory Avatar Cache):** Yayıncı profil fotoğrafları bellek içine alınıp thread-safe şekilde donduruldu (`Freeze()`). Liste kaydırılırken disk I/O ve görsel yeniden çizim maliyeti tamamen ortadan kaldırıldı.
|
||||
- **⚡ Asenkron Emote Birleştirme (Single-Flight Emotes):** Yoğun sohbette aynı anda geçen popüler ifadeler (örn. KEKW, LUL) eş zamanlı olarak tek bir asenkron görevle indirilip önbelleğe alınır; CPU ve ağ yükü sıfıra indirildi.
|
||||
- **🛡 UI Thread Koruma & Non-Blocking Polling:** Arka planda çalışan canlı yayın durum kontrolleri ve avatar yüklemeleri, UI iş parçacığını asla bloke etmeyecek şekilde `DispatcherPriority.Background` asenkron çağrılarına dönüştürüldü. Pencereler ve menüler her an yağ gibi akıcı kalır.
|
||||
|
||||
### 🟢 v1.5.0 (28 Ekim 2026)
|
||||
- **⚡ Akıcı ve Kesintisiz Canlı Sohbet (Background Dispatcher & Batching):** Canlı sohbette mesajların birkaç saniye sonra tıkanması ve akmaması sorunu tamamen çözüldü. Gelen mesajlar non-blocking kuyruk (`ConcurrentQueue`) ve 75 ms toplu arka plan işleme (`DispatcherTimer`) ile UI'ya aktarılıyor; 100.000 izleyicili yayınlarda dahi sohbet su gibi akıyor.
|
||||
- **🛡 UI Virtualization Entegrasyonu:** Sohbet kutusuna UI sanallaştırma ve geri dönüşüm (`Recycling`) eklendi, gereksiz DOM ölçümleri ve CPU darboğazı ortadan kaldırıldı.
|
||||
- **🎯 Havada Kalan/Bozulan Kalite Menüsü Yerel Açılır Menüye (ContextMenu) Taşındı:** WinForms (`WindowsFormsHost` / `VlcPanel`) ve WebView2 üzerindeki WPF Airspace (saydam popup çakışması) nedeniyle oluşan donma ve bug'lar tamamen giderildi. Artık YouTube/Twitch tarzı tıklandığında anında açılan, seçili kaliteyi tik işaretiyle (✓) gösteren şık ve sıfır hatalı bir kalite menüsü bulunuyor.
|
||||
|
||||
### 🟢 v1.4.0 (28 Ekim 2026)
|
||||
- **💬 Canlı Sohbet Bağlantı Sorunu Düzeltildi:** Kick'in yenilediği güncel Pusher WebSocket protokolü ve anahtarı entegre edildi. Artık tüm yayıncıların canlı sohbet akışları anında ve kesintisiz bağlanıyor.
|
||||
- **🔍 Kalite Seçim Kutusu Büyütüldü ve Ferahlatıldı:** Oynatıcı çubuğundaki kalite kutucuğu genişletildi, yazıların dikey/yatay kırpılması ve sıkışıklık tamamen giderildi; okunabilir, şık ve ferah bir tasarıma kavuşturuldu.
|
||||
- **🛑 Kesin Kapanış & Windows Job Object ile VLC Süreç Temizliği:** Uygulama kapatıldığında VLC veya alt süreçlerin arkada asılı kalması engellendi. Windows Job Object (`KILL_ON_JOB_CLOSE`) ile işletim sistemi seviyesinde tüm süreçler anında ve temiz şekilde sonlandırılır.
|
||||
- **🛡 Çift Açılma İyileştirmesi:** İkinci örnek açılmaya çalışıldığında modal kutu bekletmeden mevcut açık pencereyi sessizce öne getirir ve yeni örneği anında sonlandırır.
|
||||
|
||||
### 🟢 v1.3.0 (28 Ekim 2026)
|
||||
- **⚙ Oynatıcı İçi Anlık Kalite Seçimi:** Yayın çözünürlüğü ve kalite seçimi (`best`, `1080p60`, `720p60`, `720p`, `480p`, `360p`, `160p`, `audio_only`) doğrudan video oynatıcı araç çubuğuna taşındı.
|
||||
- **⚡ Ultra Hızlı Pencere İçi VLC Motoru:** Streamlink/Cloudflare bekleme ve donma sorunları tamamen giderildi. Kick AWS IVS master playlisti doğrudan bellek içinde ayrıştırılarak VLC'ye iletiliyor; yayınlar 0.3 saniyede gecikmesiz açılıyor.
|
||||
- **🎨 Aktif Oynatıcı Göstergesi:** `🌐 Web` ve `🎬 VLC` butonları, o anda hangi motorun oynatıldığını parlayan renkli vurgularla anında gösterir.
|
||||
- **🧹 Sadeleştirilmiş Ayarlar:** Kullanıcı deneyimini bozan varsayılan oynatıcı ve kalite ayarları Ayarlar sekmesinden kaldırılarak oynatıcıya entegre edildi.
|
||||
|
||||
### 🟢 v1.2.0 (27 Ekim 2026)
|
||||
- **🎬 Pencere İçi VLC Desteği:** WinForms HWND entegrasyonuyla harici pencere açmadan uygulama içinde VLC desteği.
|
||||
- **💬 Split-View Yan Sohbet Paneli:** Ana pencerenin sağ tarafında açılıp kapanan yerleşik Kick sohbet çekmecesi.
|
||||
- **⊞ 2x2 Çoklu Yayın (Squad View):** 4 canlı yayını aynı anda izleme stüdyosu.
|
||||
- **😀 Kick Emote Çizimi:** Kick sohbetinde özel emote'ların görsel olarak çizilmesi.
|
||||
- **🔔 Gelişmiş Bildirimler:** Kategori değişikliği ve anahtar kelime alarmları.
|
||||
- **🛡 Tekil Çalışma (Single Instance):** Çift açılmayı engelleme ve temiz arka plan kapanışı.
|
||||
|
||||
---
|
||||
|
||||
## 📄 Lisans
|
||||
|
||||
Bu proje [MIT Lisansı](./LICENSE) altında lisanslanmıştır.
|
||||
Bu proje [MIT Lisansı](./LICENSE) altında lisanslanmıştır. • Licensed under the [MIT License](./LICENSE).
|
||||
|
|
|
|||
13
index.html
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<!doctype html>
|
||||
<html lang="tr" class="dark h-full select-none">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/png" href="/favicon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>LD KickWatch</title>
|
||||
</head>
|
||||
<body class="h-full text-kick-text font-sans antialiased overflow-hidden">
|
||||
<div id="root" class="h-full w-full"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
#define MyAppName "LD KickWatch"
|
||||
#define MyAppVersion "1.8.0"
|
||||
#define MyAppPublisher "LilDosto"
|
||||
#define MyAppURL "https://github.com/LilDosto/LD-KickWatch"
|
||||
#define MyAppExeName "LDKickWatch.exe"
|
||||
|
||||
[Setup]
|
||||
AppId={{E684C0F7-862F-4DA1-9126-787F637C5892}
|
||||
AppName={#MyAppName}
|
||||
AppVersion={#MyAppVersion}
|
||||
AppPublisher={#MyAppPublisher}
|
||||
AppPublisherURL={#MyAppURL}
|
||||
AppSupportURL={#MyAppURL}
|
||||
AppUpdatesURL={#MyAppURL}/releases
|
||||
DefaultDirName={localappdata}\Programs\{#MyAppName}
|
||||
DefaultGroupName={#MyAppName}
|
||||
DisableProgramGroupPage=yes
|
||||
LicenseFile=..\LICENSE
|
||||
PrivilegesRequired=lowest
|
||||
OutputDir=..\publish
|
||||
OutputBaseFilename=LD-KickWatch-Setup-v1.8.0
|
||||
SetupIconFile=..\src\KickStreamHub\Resources\app.ico
|
||||
UninstallDisplayIcon={app}\{#MyAppExeName}
|
||||
Compression=lzma2/ultra64
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
CloseApplications=yes
|
||||
CloseApplicationsFilter=*LDKickWatch.exe*
|
||||
|
||||
[Languages]
|
||||
Name: "turkish"; MessagesFile: "compiler:Languages\Turkish.isl"
|
||||
Name: "english"; MessagesFile: "compiler:Default.isl"
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"
|
||||
|
||||
[Files]
|
||||
Source: "..\publish\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion
|
||||
|
||||
[Icons]
|
||||
Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
|
||||
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon
|
||||
|
||||
[Run]
|
||||
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
|
||||
3239
package-lock.json
generated
Normal file
41
package.json
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
{
|
||||
"name": "ld-kickwatch",
|
||||
"private": true,
|
||||
"version": "2.6.12",
|
||||
"description": "LD KickWatch - Modern Desktop Livestreaming Studio & Live Chat Client for Kick.com (Tauri v2, Rust, React)",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.2.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.2.0",
|
||||
"@tauri-apps/plugin-fs": "^2.2.0",
|
||||
"@tauri-apps/plugin-notification": "^2.2.0",
|
||||
"@tauri-apps/plugin-process": "^2.2.0",
|
||||
"@tauri-apps/plugin-shell": "^2.2.0",
|
||||
"@tauri-apps/plugin-updater": "^2.14.1",
|
||||
"clsx": "^2.1.1",
|
||||
"framer-motion": "^11.18.2",
|
||||
"lucide-react": "^0.474.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"tailwind-merge": "^2.6.0",
|
||||
"zustand": "^5.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.2.0",
|
||||
"@types/node": "^22.10.7",
|
||||
"@types/react": "^18.3.18",
|
||||
"@types/react-dom": "^18.3.5",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.5.1",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "^5.7.3",
|
||||
"vite": "^6.0.7"
|
||||
}
|
||||
}
|
||||
6
postcss.config.js
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
BIN
public/favicon.ico
Normal file
|
After Width: | Height: | Size: 174 KiB |
BIN
public/favicon.png
Normal file
|
After Width: | Height: | Size: 2.5 KiB |
BIN
public/logo.png
Normal file
|
After Width: | Height: | Size: 282 KiB |
6544
src-tauri/Cargo.lock
generated
Normal file
59
src-tauri/Cargo.toml
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
[package]
|
||||
name = "ld-kickwatch"
|
||||
version = "2.6.12"
|
||||
description = "LD KickWatch - Modern Desktop Livestreaming Studio & Live Chat Client for Kick.com"
|
||||
authors = ["LilDosto"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/LilDosto/LD-KickWatch"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "ld_kickwatch_lib"
|
||||
crate-type = ["lib"]
|
||||
test = false
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.0.5", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2.5.3", features = ["tray-icon"] }
|
||||
tauri-plugin-shell = "2"
|
||||
tauri-plugin-notification = "2"
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-fs = "2"
|
||||
tauri-plugin-process = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
tauri-plugin-single-instance = "2.2.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
thiserror = "2.0"
|
||||
tokio = { version = "1.42", features = ["full"] }
|
||||
tokio-tungstenite = { version = "0.26", features = ["native-tls"] }
|
||||
futures-util = "0.3"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "native-tls", "gzip", "brotli", "http2"] }
|
||||
regex = "1.11"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
rodio = { version = "0.20", default-features = false, features = ["wav"] }
|
||||
dirs = "6.0"
|
||||
base64 = "0.22"
|
||||
log = "0.4"
|
||||
libloading = "0.8"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.59", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_Threading"
|
||||
] }
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
strip = true
|
||||
3
src-tauri/build.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fn main() {
|
||||
tauri_build::build();
|
||||
}
|
||||
29
src-tauri/capabilities/default.json
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "LD KickWatch scoped least-privilege security capabilities",
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-unminimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-unmaximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-is-maximized",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-fullscreen",
|
||||
"core:window:allow-is-fullscreen",
|
||||
"shell:default",
|
||||
"notification:default",
|
||||
"dialog:default",
|
||||
"process:default",
|
||||
"updater:default"
|
||||
]
|
||||
}
|
||||
7
src-tauri/capabilities/kick-auth.json
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "kick-auth",
|
||||
"description": "Kick login window: remote page gets no Tauri IPC access, only its own webview",
|
||||
"windows": ["kick-auth"],
|
||||
"permissions": ["core:default"]
|
||||
}
|
||||
1
src-tauri/gen/schemas/acl-manifests.json
Normal file
1
src-tauri/gen/schemas/capabilities.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"default":{"identifier":"default","description":"LD KickWatch scoped least-privilege security capabilities","local":true,"windows":["main"],"permissions":["core:default","core:window:allow-close","core:window:allow-hide","core:window:allow-show","core:window:allow-minimize","core:window:allow-unminimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-toggle-maximize","core:window:allow-is-maximized","core:window:allow-set-focus","core:window:allow-start-dragging","core:window:allow-set-fullscreen","core:window:allow-is-fullscreen","shell:default","notification:default","dialog:default","process:default","updater:default"]},"kick-auth":{"identifier":"kick-auth","description":"Kick login window: remote page gets no Tauri IPC access, only its own webview","local":true,"windows":["kick-auth"],"permissions":["core:default"]}}
|
||||
6572
src-tauri/gen/schemas/desktop-schema.json
Normal file
6572
src-tauri/gen/schemas/windows-schema.json
Normal file
BIN
src-tauri/icons/128x128.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
src-tauri/icons/128x128@2x.png
Normal file
|
After Width: | Height: | Size: 78 KiB |
BIN
src-tauri/icons/32x32.png
Normal file
|
After Width: | Height: | Size: 2.5 KiB |
BIN
src-tauri/icons/icon.ico
Normal file
|
After Width: | Height: | Size: 174 KiB |
BIN
src-tauri/icons/icon.png
Normal file
|
After Width: | Height: | Size: 282 KiB |
9
src-tauri/installer-hooks.nsh
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
; LD KickWatch NSIS hooks
|
||||
; The app stores its config, logs and the WebView2 profile (Kick session cookies)
|
||||
; outside the install directory, so a plain uninstall would leave them behind.
|
||||
|
||||
!macro NSIS_HOOK_POSTUNINSTALL
|
||||
RMDir /r "$LOCALAPPDATA\LDKickWatch"
|
||||
RMDir /r "$LOCALAPPDATA\com.ldkickwatch.desktop"
|
||||
RMDir /r "$APPDATA\LDKickWatch"
|
||||
!macroend
|
||||
13
src-tauri/resources/README.txt
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
LD KickWatch - libmpv Native Player DLL Yerlesimi
|
||||
|
||||
Windows x86_64 uyumlu `libmpv-2.dll` dosyasini bu klasore yerlestirin:
|
||||
src-tauri/resources/libmpv-2.dll
|
||||
|
||||
Resmi kaynak:
|
||||
https://github.com/shinchiro/mpv-winbuild-cmake/releases
|
||||
("mpv-dev-x86_64-*.7z" veya "mpv-dev-x86_64-v3-*.7z" arsivi icindeki `libmpv-2.dll`)
|
||||
|
||||
`tauri.conf.json` icindeki `"resources": { "resources": "" }` kurali sayesinde:
|
||||
- `cargo tauri dev` ve `cargo tauri build` calistirildiginda bu klasordeki
|
||||
`libmpv-2.dll` otomatik olarak cikti `ld-kickwatch.exe` yanina (ve NSIS/MSI
|
||||
kurulum paketine) kopyalanir.
|
||||
190
src-tauri/src/commands/channel.rs
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
use crate::error::AppError;
|
||||
use crate::models::ChannelCard;
|
||||
use crate::state::AppState;
|
||||
use tauri::State;
|
||||
|
||||
pub fn clean_channel_name(raw: &str) -> String {
|
||||
// Users paste all sorts of shapes: "@name", "https://kick.com/name/",
|
||||
// " kick.com/name " or even "na me" — normalise everything to a bare slug.
|
||||
let compact: String = raw.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
compact
|
||||
.trim_start_matches('@')
|
||||
.trim_start_matches("https://kick.com/")
|
||||
.trim_start_matches("http://kick.com/")
|
||||
.trim_start_matches("https://www.kick.com/")
|
||||
.trim_start_matches("kick.com/")
|
||||
.trim_end_matches('/')
|
||||
.to_lowercase()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_channels(state: State<'_, AppState>) -> Result<Vec<ChannelCard>, AppError> {
|
||||
Ok(state.polling.get_cached_or_placeholder_cards().await)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn add_channel(
|
||||
channel_name: String,
|
||||
group_name: Option<String>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Vec<ChannelCard>, AppError> {
|
||||
let clean = clean_channel_name(&channel_name);
|
||||
|
||||
if clean.is_empty() {
|
||||
return Err(AppError::InvalidInput("Kanal adı boş olamaz".to_string()));
|
||||
}
|
||||
|
||||
{
|
||||
let mut cfg = state.config.write().await;
|
||||
if !cfg.favorites.iter().any(|f| clean_channel_name(f) == clean) {
|
||||
cfg.favorites.push(clean.clone());
|
||||
}
|
||||
if let Some(grp) = group_name {
|
||||
if !grp.trim().is_empty() {
|
||||
cfg.channel_groups
|
||||
.insert(clean.clone(), grp.trim().to_string());
|
||||
}
|
||||
}
|
||||
state.config_service.save(&cfg)?;
|
||||
}
|
||||
|
||||
state.polling.invalidate_cooldown().await;
|
||||
// Refresh immediately
|
||||
refresh_channels(state).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn remove_channel(
|
||||
channel_name: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Vec<ChannelCard>, AppError> {
|
||||
let clean = clean_channel_name(&channel_name);
|
||||
|
||||
{
|
||||
let mut cfg = state.config.write().await;
|
||||
cfg.favorites.retain(|f| clean_channel_name(f) != clean);
|
||||
cfg.channel_groups.remove(&clean);
|
||||
state.config_service.save(&cfg)?;
|
||||
}
|
||||
|
||||
state.player.stop(&clean);
|
||||
state.polling.sync_cache_from_config().await;
|
||||
state.polling.invalidate_cooldown().await;
|
||||
|
||||
refresh_channels(state).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn set_channel_group(
|
||||
channel_name: String,
|
||||
group_name: Option<String>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), AppError> {
|
||||
let clean = clean_channel_name(&channel_name);
|
||||
|
||||
{
|
||||
let mut cfg = state.config.write().await;
|
||||
if let Some(grp) = group_name {
|
||||
if grp.trim().is_empty() {
|
||||
cfg.channel_groups.remove(&clean);
|
||||
} else {
|
||||
cfg.channel_groups.insert(clean, grp.trim().to_string());
|
||||
}
|
||||
} else {
|
||||
cfg.channel_groups.remove(&clean);
|
||||
}
|
||||
state.config_service.save(&cfg)?;
|
||||
}
|
||||
|
||||
state.polling.sync_cache_from_config().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn refresh_channels(state: State<'_, AppState>) -> Result<Vec<ChannelCard>, AppError> {
|
||||
Ok(state.polling.poll_now().await)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn import_channels(
|
||||
raw_input: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<usize, AppError> {
|
||||
let mut added_count = 0;
|
||||
let mut to_add = Vec::new();
|
||||
|
||||
// Check if input is JSON
|
||||
if let Ok(json_val) = serde_json::from_str::<serde_json::Value>(&raw_input) {
|
||||
if let Some(arr) = json_val.as_array() {
|
||||
for item in arr {
|
||||
if let Some(s) = item.as_str() {
|
||||
let clean = clean_channel_name(s);
|
||||
if !clean.is_empty() {
|
||||
to_add.push(clean);
|
||||
}
|
||||
} else if let Some(obj) = item.as_object() {
|
||||
if let Some(name) = obj
|
||||
.get("name")
|
||||
.or_else(|| obj.get("channel_name"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
let clean = clean_channel_name(name);
|
||||
if !clean.is_empty() {
|
||||
to_add.push(clean);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Line-by-line or comma separated
|
||||
for part in raw_input.split([',', '\n', '\r', ';']) {
|
||||
let clean = clean_channel_name(part);
|
||||
if !clean.is_empty() {
|
||||
to_add.push(clean);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let mut cfg = state.config.write().await;
|
||||
for ch in to_add {
|
||||
if !cfg.favorites.iter().any(|f| clean_channel_name(f) == ch) {
|
||||
cfg.favorites.push(ch);
|
||||
added_count += 1;
|
||||
}
|
||||
}
|
||||
if added_count > 0 {
|
||||
state.config_service.save(&cfg)?;
|
||||
}
|
||||
}
|
||||
|
||||
if added_count > 0 {
|
||||
state.polling.invalidate_cooldown().await;
|
||||
}
|
||||
let _ = refresh_channels(state).await;
|
||||
|
||||
Ok(added_count)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn export_channels(state: State<'_, AppState>) -> Result<String, AppError> {
|
||||
let cfg = state.config.read().await;
|
||||
let export_data = serde_json::json!({
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"exported_at": chrono::Utc::now().to_rfc3339(),
|
||||
"favorites": cfg.favorites,
|
||||
"channel_groups": cfg.channel_groups,
|
||||
});
|
||||
serde_json::to_string_pretty(&export_data).map_err(AppError::Serialization)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_top_tr_channels(state: State<'_, AppState>) -> Result<Vec<ChannelCard>, AppError> {
|
||||
state.api.fetch_top_tr_livestreams(12).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_small_tr_channels(state: State<'_, AppState>) -> Result<Vec<ChannelCard>, AppError> {
|
||||
state.api.fetch_small_tr_livestreams(15).await
|
||||
}
|
||||
53
src-tauri/src/commands/chat.rs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
use crate::error::AppError;
|
||||
use crate::state::AppState;
|
||||
use tauri::State;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn connect_chat(
|
||||
channel_name: String,
|
||||
chatroom_id: Option<i64>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<i64, AppError> {
|
||||
let clean = channel_name
|
||||
.trim()
|
||||
.trim_start_matches('@')
|
||||
.trim_start_matches("https://kick.com/")
|
||||
.trim_start_matches("http://kick.com/")
|
||||
.trim_start_matches("kick.com/")
|
||||
.trim_end_matches('/')
|
||||
.to_lowercase();
|
||||
|
||||
if clean.is_empty() {
|
||||
return Err(AppError::InvalidInput("Kanal adı belirtilmedi".to_string()));
|
||||
}
|
||||
|
||||
let target_room_id = match chatroom_id {
|
||||
Some(id) if id > 0 => id,
|
||||
_ => {
|
||||
let channel_data = state.api.get_channel(&clean).await?;
|
||||
channel_data.chatroom.and_then(|c| c.id).ok_or_else(|| {
|
||||
AppError::General(format!(
|
||||
"'{}' kanalına ait sohbet odası ID'si bulunamadı",
|
||||
clean
|
||||
))
|
||||
})?
|
||||
}
|
||||
};
|
||||
|
||||
state.chat.connect(&clean, target_room_id).await?;
|
||||
|
||||
Ok(target_room_id)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn disconnect_chat(state: State<'_, AppState>) -> Result<(), AppError> {
|
||||
state.chat.disconnect().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_chat_status(
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Option<(String, i64)>, AppError> {
|
||||
Ok(state.chat.get_current_channel().await)
|
||||
}
|
||||
89
src-tauri/src/commands/config.rs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
use crate::error::AppError;
|
||||
use crate::models::AppConfig;
|
||||
use crate::services::{AppLogger, ShortcutService, SoundService};
|
||||
use crate::state::AppState;
|
||||
use std::process::Command;
|
||||
use tauri::State;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_config(state: State<'_, AppState>) -> Result<AppConfig, AppError> {
|
||||
let cfg = state.config.read().await;
|
||||
Ok(cfg.clone())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn update_config(
|
||||
new_config: AppConfig,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<AppConfig, AppError> {
|
||||
state.config_service.save(&new_config)?;
|
||||
|
||||
let mut cfg = state.config.write().await;
|
||||
*cfg = new_config.clone();
|
||||
|
||||
Ok(new_config)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn play_test_sound(
|
||||
custom_sound_path: Option<String>,
|
||||
is_alert: Option<bool>,
|
||||
_state: State<'_, AppState>,
|
||||
) -> Result<(), AppError> {
|
||||
SoundService::play_notification(custom_sound_path.as_deref(), is_alert.unwrap_or(false))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn create_desktop_shortcut() -> Result<String, AppError> {
|
||||
ShortcutService::create_desktop_shortcut()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn open_logs_dir() -> Result<String, AppError> {
|
||||
let dir = AppLogger::get_instance()
|
||||
.map(|l| l.get_log_dir())
|
||||
.unwrap_or_else(|| {
|
||||
let mut d = dirs::data_local_dir().unwrap_or_else(|| std::path::PathBuf::from("."));
|
||||
d.push("LDKickWatch");
|
||||
d
|
||||
});
|
||||
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
Command::new("explorer")
|
||||
.arg(dir.as_os_str())
|
||||
.spawn()
|
||||
.map_err(AppError::Io)?;
|
||||
}
|
||||
|
||||
Ok(dir.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_recent_logs() -> Result<Vec<String>, AppError> {
|
||||
let logs = AppLogger::get_instance()
|
||||
.map(|l| l.get_recent_logs())
|
||||
.unwrap_or_default();
|
||||
Ok(logs)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn clear_logs() -> Result<(), AppError> {
|
||||
if let Some(logger) = AppLogger::get_instance() {
|
||||
logger.clear_logs()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn reset_config(state: State<'_, AppState>) -> Result<AppConfig, AppError> {
|
||||
let default_cfg = AppConfig::default();
|
||||
state.config_service.save(&default_cfg)?;
|
||||
|
||||
let mut cfg = state.config.write().await;
|
||||
*cfg = default_cfg.clone();
|
||||
|
||||
Ok(default_cfg)
|
||||
}
|
||||
841
src-tauri/src/commands/kick.rs
Normal file
|
|
@ -0,0 +1,841 @@
|
|||
use crate::error::AppError;
|
||||
use crate::services::kick_auth::{
|
||||
cookie_header, find_cookie, format_emotes, normalize_session_token, percent_decode,
|
||||
profile_from_json, KickAuthContext, KickProfile,
|
||||
};
|
||||
use crate::state::AppState;
|
||||
use base64::Engine;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder};
|
||||
|
||||
static EMOTE_IMAGE_CACHE: LazyLock<Mutex<HashMap<String, String>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KickEmote {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub category: String,
|
||||
#[serde(default)]
|
||||
pub subscribers_only: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct KickSendResult {
|
||||
pub ok: bool,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
fn auth_context(cfg: &crate::models::AppConfig) -> KickAuthContext {
|
||||
KickAuthContext {
|
||||
token: cfg.kick_token.clone(),
|
||||
cookie_header: cfg.kick_cookies.clone(),
|
||||
xsrf_token: cfg.kick_xsrf.clone(),
|
||||
user_agent: cfg.kick_user_agent.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_profile(
|
||||
api: &crate::services::KickApiService,
|
||||
auth: &KickAuthContext,
|
||||
) -> Result<KickProfile, AppError> {
|
||||
let (status, body) = api
|
||||
.authed_json("GET", "https://kick.com/api/v1/user", None, auth)
|
||||
.await?;
|
||||
|
||||
if status == 401 || status == 403 {
|
||||
return Err(AppError::General(
|
||||
"Kick oturumu doğrulanamadı. Lütfen yeniden giriş yapın.".to_string(),
|
||||
));
|
||||
}
|
||||
if !(200..300).contains(&status) {
|
||||
return Err(AppError::General(format!(
|
||||
"Kick kullanıcı doğrulaması HTTP {} döndürdü",
|
||||
status
|
||||
)));
|
||||
}
|
||||
|
||||
profile_from_json(&body)
|
||||
}
|
||||
|
||||
async fn persist_profile(
|
||||
state: &AppState,
|
||||
auth: &KickAuthContext,
|
||||
profile: &KickProfile,
|
||||
) -> Result<(), AppError> {
|
||||
let snapshot = {
|
||||
let mut cfg = state.config.write().await;
|
||||
cfg.kick_token = auth.token.clone();
|
||||
cfg.kick_cookies = auth.cookie_header.clone();
|
||||
cfg.kick_xsrf = auth.xsrf_token.clone();
|
||||
cfg.kick_user_agent = auth.user_agent.clone();
|
||||
cfg.kick_user_id = Some(profile.id);
|
||||
cfg.kick_username = profile.username.clone();
|
||||
cfg.kick_avatar = profile.avatar_url.clone();
|
||||
cfg.clone()
|
||||
};
|
||||
state.config_service.save(&snapshot)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn kick_open_login(app: AppHandle) -> Result<(), AppError> {
|
||||
if let Some(existing) = app.get_webview_window("kick-auth") {
|
||||
let _ = existing.show();
|
||||
let _ = existing.set_focus();
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let url = "https://kick.com/login"
|
||||
.parse()
|
||||
.map_err(|_| AppError::InvalidInput("Kick giriş adresi geçersiz".to_string()))?;
|
||||
|
||||
let window = WebviewWindowBuilder::new(&app, "kick-auth", WebviewUrl::External(url))
|
||||
.title("Kick Hesabına Giriş Yap - LD KickWatch")
|
||||
.inner_size(480.0, 680.0)
|
||||
.center()
|
||||
.resizable(true)
|
||||
.focused(true)
|
||||
.build()
|
||||
.map_err(|err| AppError::General(format!("Giriş penceresi açılamadı: {}", err)))?;
|
||||
|
||||
let _ = window.eval("document.title = 'Kick Hesabına Giriş Yap - LD KickWatch';");
|
||||
|
||||
let poll_handle = app.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
for _ in 0..300u32 {
|
||||
let Some(status) = poll_auth_once(&poll_handle).await else {
|
||||
// window closed by the user
|
||||
return;
|
||||
};
|
||||
match status {
|
||||
PollOutcome::Pending => {}
|
||||
PollOutcome::Authenticated(profile) => {
|
||||
if let Some(window) = poll_handle.get_webview_window("kick-auth") {
|
||||
let _ = window.close();
|
||||
}
|
||||
let _ = poll_handle.emit("kick-auth-changed", Some(profile));
|
||||
if let Some(state) = poll_handle.try_state::<AppState>() {
|
||||
let ctx = state.polling.context();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
ctx.invalidate_cooldown().await;
|
||||
let _ = ctx.poll_now().await;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum PollOutcome {
|
||||
Pending,
|
||||
Authenticated(KickProfile),
|
||||
}
|
||||
|
||||
async fn poll_auth_once(app: &AppHandle) -> Option<PollOutcome> {
|
||||
let window = app.get_webview_window("kick-auth")?;
|
||||
let url = "https://kick.com".parse().ok()?;
|
||||
let cookies = window.cookies_for_url(url).ok()?;
|
||||
|
||||
let pairs: Vec<(String, String)> = cookies
|
||||
.iter()
|
||||
.map(|cookie| (cookie.name().to_string(), cookie.value().to_string()))
|
||||
.collect();
|
||||
|
||||
let raw_token = find_cookie(&pairs, "session_token")?;
|
||||
let token = normalize_session_token(raw_token);
|
||||
if token.is_empty() {
|
||||
return Some(PollOutcome::Pending);
|
||||
}
|
||||
|
||||
let auth = KickAuthContext {
|
||||
token,
|
||||
cookie_header: cookie_header(&pairs),
|
||||
xsrf_token: find_cookie(&pairs, "XSRF-TOKEN")
|
||||
.map(percent_decode)
|
||||
.unwrap_or_default(),
|
||||
user_agent: String::new(),
|
||||
};
|
||||
|
||||
let state = app.try_state::<AppState>()?;
|
||||
match validate_profile(&state.api, &auth).await {
|
||||
Ok(profile) => {
|
||||
if persist_profile(&state, &auth, &profile).await.is_err() {
|
||||
return Some(PollOutcome::Pending);
|
||||
}
|
||||
let _ = window.emit("kick-auth-detected", &profile);
|
||||
Some(PollOutcome::Authenticated(profile))
|
||||
}
|
||||
Err(_) => Some(PollOutcome::Pending),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn kick_auth_profile(state: State<'_, AppState>) -> Result<Option<KickProfile>, AppError> {
|
||||
let cfg = state.config.read().await;
|
||||
if cfg.kick_token.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(KickProfile {
|
||||
id: cfg.kick_user_id.unwrap_or(0),
|
||||
username: cfg.kick_username.clone(),
|
||||
avatar_url: cfg.kick_avatar.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn kick_manual_token(
|
||||
token: String,
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<KickProfile, AppError> {
|
||||
let normalized = normalize_session_token(&token);
|
||||
if normalized.is_empty() {
|
||||
return Err(AppError::InvalidInput(
|
||||
"Geçerli bir session_token girilmedi".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let auth = KickAuthContext {
|
||||
token: normalized,
|
||||
..Default::default()
|
||||
};
|
||||
let profile = validate_profile(&state.api, &auth).await?;
|
||||
persist_profile(&state, &auth, &profile).await?;
|
||||
let _ = app.emit("kick-auth-changed", Some(profile.clone()));
|
||||
let ctx = state.polling.context();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
ctx.invalidate_cooldown().await;
|
||||
let _ = ctx.poll_now().await;
|
||||
});
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn kick_logout(app: AppHandle, state: State<'_, AppState>) -> Result<(), AppError> {
|
||||
let snapshot = {
|
||||
let mut cfg = state.config.write().await;
|
||||
cfg.kick_token.clear();
|
||||
cfg.kick_cookies.clear();
|
||||
cfg.kick_xsrf.clear();
|
||||
cfg.kick_user_agent.clear();
|
||||
cfg.kick_user_id = None;
|
||||
cfg.kick_username.clear();
|
||||
cfg.kick_avatar.clear();
|
||||
cfg.favorites.clear();
|
||||
cfg.channel_groups.clear();
|
||||
cfg.clone()
|
||||
};
|
||||
state.config_service.save(&snapshot)?;
|
||||
state.config_service.clear_channel_caches();
|
||||
state.polling.clear_all_cached_channels().await;
|
||||
|
||||
// Wipe the WebView2 profile as well, otherwise Kick's session cookies keep
|
||||
// the account "remembered" after logout / uninstall.
|
||||
for label in ["kick-auth", "main"] {
|
||||
if let Some(window) = app.get_webview_window(label) {
|
||||
if label == "kick-auth" {
|
||||
let _ = window.close();
|
||||
}
|
||||
let _ = window.clear_all_browsing_data();
|
||||
}
|
||||
}
|
||||
let _ = app.emit("kick-auth-changed", Option::<KickProfile>::None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn kick_sync_followed(state: State<'_, AppState>) -> Result<usize, AppError> {
|
||||
let cfg = state.config.read().await.clone();
|
||||
if cfg.kick_token.is_empty() {
|
||||
return Err(AppError::General(
|
||||
"Takip listesini senkronize etmek için Kick hesabına giriş yapın".to_string(),
|
||||
));
|
||||
}
|
||||
let auth = auth_context(&cfg);
|
||||
|
||||
// Stage 1 (<500ms): fetch live-first pages in parallel and push live channels to UI immediately
|
||||
let (mut entries, next_cursor, all_done) = state.api.fetch_followed_live_batch(&auth).await?;
|
||||
|
||||
state
|
||||
.polling
|
||||
.apply_followed_entries(&entries, true, false)
|
||||
.await;
|
||||
|
||||
// Stage 2: collect complete followed list (Single Source of Truth) without stale/unfollowed channels
|
||||
if !all_done {
|
||||
if let Some(cursor) = next_cursor {
|
||||
let rest = state.api.fetch_followed_remaining(&auth, cursor, 500).await;
|
||||
let mut existing_slugs: HashSet<String> =
|
||||
entries.iter().map(|e| e.channel_slug.clone()).collect();
|
||||
for entry in rest {
|
||||
if existing_slugs.insert(entry.channel_slug.clone()) {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut unique_slugs: Vec<String> = Vec::with_capacity(entries.len());
|
||||
let mut seen_slugs = HashSet::new();
|
||||
for entry in &entries {
|
||||
if !entry.channel_slug.is_empty() && seen_slugs.insert(entry.channel_slug.clone()) {
|
||||
unique_slugs.push(entry.channel_slug.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let added = {
|
||||
let mut cfg = state.config.write().await;
|
||||
let prev_set: HashSet<String> = cfg
|
||||
.favorites
|
||||
.iter()
|
||||
.map(|f| crate::commands::channel::clean_channel_name(f))
|
||||
.collect();
|
||||
let added_count = unique_slugs
|
||||
.iter()
|
||||
.filter(|slug| !prev_set.contains(*slug))
|
||||
.count();
|
||||
|
||||
if cfg.favorites != unique_slugs {
|
||||
cfg.favorites = unique_slugs;
|
||||
cfg.channel_groups
|
||||
.retain(|k, _| seen_slugs.contains(&crate::commands::channel::clean_channel_name(k)));
|
||||
state.config_service.save(&cfg)?;
|
||||
}
|
||||
added_count
|
||||
};
|
||||
|
||||
state
|
||||
.polling
|
||||
.apply_followed_entries(&entries, false, true)
|
||||
.await;
|
||||
|
||||
Ok(added)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn kick_send_message(
|
||||
chatroom_id: i64,
|
||||
content: String,
|
||||
reply: Option<serde_json::Value>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<KickSendResult, AppError> {
|
||||
let cfg = state.config.read().await.clone();
|
||||
if cfg.kick_token.is_empty() {
|
||||
return Err(AppError::General(
|
||||
"Mesaj göndermek için Kick hesabına giriş yapın".to_string(),
|
||||
));
|
||||
}
|
||||
let text = content.trim();
|
||||
if text.is_empty() {
|
||||
return Err(AppError::InvalidInput("Mesaj boş olamaz".to_string()));
|
||||
}
|
||||
if text.len() > 500 {
|
||||
return Err(AppError::InvalidInput(
|
||||
"Mesaj 500 karakterden uzun olamaz".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let auth = auth_context(&cfg);
|
||||
let mut payload = json!({ "content": text, "type": "message" });
|
||||
if let Some(reply) = reply {
|
||||
payload = json!({
|
||||
"content": text,
|
||||
"type": "reply",
|
||||
"metadata": {
|
||||
"original_message": {
|
||||
"id": reply.get("id").cloned().unwrap_or(serde_json::Value::Null),
|
||||
"content": reply.get("content").cloned().unwrap_or(serde_json::Value::Null)
|
||||
},
|
||||
"original_sender": {
|
||||
"id": reply.get("senderId").cloned().unwrap_or(serde_json::Value::Null),
|
||||
"username": reply.get("senderUsername").cloned().unwrap_or(serde_json::Value::Null)
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let body = payload.to_string();
|
||||
let url = format!("https://kick.com/api/v2/messages/send/{}", chatroom_id);
|
||||
let (status, response_body) = state
|
||||
.api
|
||||
.authed_json("POST", &url, Some(&body), &auth)
|
||||
.await?;
|
||||
|
||||
if (200..300).contains(&status) {
|
||||
return Ok(KickSendResult {
|
||||
ok: true,
|
||||
message: "Mesaj gönderildi".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let kick_message = serde_json::from_str::<serde_json::Value>(&response_body)
|
||||
.ok()
|
||||
.and_then(|value| {
|
||||
value
|
||||
.get("message")
|
||||
.or_else(|| value.get("error"))
|
||||
.and_then(|field| field.as_str())
|
||||
.map(|text| text.to_string())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let friendly = match status {
|
||||
429 => "Yavaş mod açık: biraz bekleyip tekrar deneyin.".to_string(),
|
||||
401 | 403 => {
|
||||
if kick_message.is_empty() {
|
||||
"Mesaj gönderilemedi: oturum veya kanal izni yok (abone/takipçi kısıtı olabilir)."
|
||||
.to_string()
|
||||
} else {
|
||||
format!("Mesaj gönderilemedi: {}", kick_message)
|
||||
}
|
||||
}
|
||||
422 => format!(
|
||||
"Kick mesajı reddetti{}",
|
||||
if kick_message.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(": {}", kick_message)
|
||||
}
|
||||
),
|
||||
code => format!("Mesaj gönderilemedi (HTTP {})", code),
|
||||
};
|
||||
|
||||
Err(AppError::General(friendly))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn kick_channel_emotes(
|
||||
channel_slug: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Vec<KickEmote>, AppError> {
|
||||
let clean = crate::commands::channel::clean_channel_name(&channel_slug);
|
||||
let cfg = state.config.read().await.clone();
|
||||
let auth = auth_context(&cfg);
|
||||
let url = format!("https://kick.com/emotes/{}", clean);
|
||||
|
||||
let (status, body) = state.api.authed_json("GET", &url, None, &auth).await?;
|
||||
let payload = if (200..300).contains(&status) {
|
||||
body
|
||||
} else {
|
||||
state.api.public_json(&url).await?
|
||||
};
|
||||
|
||||
let value: serde_json::Value = serde_json::from_str(&payload)
|
||||
.map_err(|_| AppError::General("Emote listesi okunamadý".to_string()))?;
|
||||
|
||||
let mut emotes: Vec<KickEmote> = Vec::new();
|
||||
if let Some(groups) = value.as_array() {
|
||||
for group in groups {
|
||||
let group_id = group
|
||||
.get("id")
|
||||
.and_then(|id| {
|
||||
id.as_str()
|
||||
.map(|text| text.to_string())
|
||||
.or_else(|| id.as_i64().map(|number| number.to_string()))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let slug = group
|
||||
.get("slug")
|
||||
.and_then(|slug| slug.as_str())
|
||||
.unwrap_or("");
|
||||
|
||||
let category = match group_id.as_str() {
|
||||
"Global" => "Global",
|
||||
"Emoji" => "Emoji",
|
||||
"Collectibles" => "Collectibles",
|
||||
_ if slug == clean => "Channel",
|
||||
_ => "Subscribed",
|
||||
};
|
||||
|
||||
if let Some(items) = group.get("emotes").and_then(|emotes| emotes.as_array()) {
|
||||
for emote in items {
|
||||
let id = emote.get("id").and_then(|id| {
|
||||
id.as_str()
|
||||
.map(|text| text.to_string())
|
||||
.or_else(|| id.as_i64().map(|number| number.to_string()))
|
||||
});
|
||||
let name = emote
|
||||
.get("name")
|
||||
.and_then(|name| name.as_str())
|
||||
.map(|text| text.to_string());
|
||||
if let (Some(id), Some(name)) = (id, name) {
|
||||
emotes.push(KickEmote {
|
||||
id,
|
||||
name,
|
||||
category: category.to_string(),
|
||||
subscribers_only: emote
|
||||
.get("subscribers_only")
|
||||
.and_then(|flag| flag.as_bool())
|
||||
.unwrap_or(false),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
emotes.sort_by_key(|emote| emote.name.to_lowercase());
|
||||
emotes.dedup_by(|a, b| a.name.eq_ignore_ascii_case(&b.name) && a.id == b.id);
|
||||
Ok(emotes)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KickFollowResult {
|
||||
pub status: String,
|
||||
pub following: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KickFollowChangedEvent {
|
||||
pub channel_slug: String,
|
||||
pub following: bool,
|
||||
}
|
||||
|
||||
async fn check_follow_state_with_fallback(
|
||||
api: &crate::services::KickApiService,
|
||||
auth: &KickAuthContext,
|
||||
clean: &str,
|
||||
) -> Option<bool> {
|
||||
let url = format!("https://kick.com/api/v2/channels/{}/me", clean);
|
||||
let (mut status, mut body) = api.authed_json("GET", &url, None, auth).await.ok()?;
|
||||
|
||||
if (status == 401 || status == 403 || status == 419) && !auth.cookie_header.is_empty() {
|
||||
let bearer_only = KickAuthContext {
|
||||
token: auth.token.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
if let Ok((s2, b2)) = api.authed_json("GET", &url, None, &bearer_only).await {
|
||||
status = s2;
|
||||
body = b2;
|
||||
}
|
||||
}
|
||||
|
||||
if !(200..300).contains(&status) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let value: serde_json::Value = serde_json::from_str(&body).ok()?;
|
||||
value
|
||||
.get("is_following")
|
||||
.or_else(|| value.get("following"))
|
||||
.and_then(|flag| flag.as_bool())
|
||||
}
|
||||
|
||||
async fn apply_local_follow_change(app: &AppHandle, state: &AppState, clean: &str, follow: bool) {
|
||||
let snapshot = {
|
||||
let mut cfg = state.config.write().await;
|
||||
if follow {
|
||||
if !cfg
|
||||
.favorites
|
||||
.iter()
|
||||
.any(|favorite| crate::commands::channel::clean_channel_name(favorite) == clean)
|
||||
{
|
||||
cfg.favorites.push(clean.to_string());
|
||||
}
|
||||
} else {
|
||||
cfg.favorites
|
||||
.retain(|favorite| crate::commands::channel::clean_channel_name(favorite) != clean);
|
||||
}
|
||||
cfg.clone()
|
||||
};
|
||||
let _ = state.config_service.save(&snapshot);
|
||||
|
||||
if follow {
|
||||
state.polling.upsert_followed_channel(clean).await;
|
||||
} else {
|
||||
state.polling.remove_followed_channel(clean).await;
|
||||
}
|
||||
|
||||
let _ = app.emit(
|
||||
"kick-follow-changed",
|
||||
KickFollowChangedEvent {
|
||||
channel_slug: clean.to_string(),
|
||||
following: follow,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn kick_follow_channel(
|
||||
channel_slug: String,
|
||||
follow: bool,
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<KickFollowResult, AppError> {
|
||||
let cfg = state.config.read().await.clone();
|
||||
if cfg.kick_token.is_empty() {
|
||||
return Err(AppError::General(
|
||||
"Takip için Kick hesabına giriş yapın".to_string(),
|
||||
));
|
||||
}
|
||||
let clean = crate::commands::channel::clean_channel_name(&channel_slug);
|
||||
if clean.is_empty() {
|
||||
return Err(AppError::InvalidInput("Kanal adı geçersiz".to_string()));
|
||||
}
|
||||
|
||||
let auth = auth_context(&cfg);
|
||||
let url = format!("https://kick.com/api/v2/channels/{}/follow", clean);
|
||||
let method = if follow { "POST" } else { "DELETE" };
|
||||
let body = if follow { Some("{}".to_string()) } else { None };
|
||||
|
||||
let (mut status, mut response_body) = state
|
||||
.api
|
||||
.authed_json(method, &url, body.as_deref(), &auth)
|
||||
.await?;
|
||||
|
||||
// Retry without stale session/CSRF cookies if Kick rejects old XSRF cookies
|
||||
if (status == 419 || status == 403 || status == 401) && !auth.cookie_header.is_empty() {
|
||||
let bearer_only = KickAuthContext {
|
||||
token: auth.token.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
if let Ok((s2, b2)) = state
|
||||
.api
|
||||
.authed_json(method, &url, body.as_deref(), &bearer_only)
|
||||
.await
|
||||
{
|
||||
status = s2;
|
||||
response_body = b2;
|
||||
}
|
||||
}
|
||||
|
||||
if (200..300).contains(&status) || status == 204 {
|
||||
apply_local_follow_change(&app, &state, &clean, follow).await;
|
||||
return Ok(KickFollowResult {
|
||||
status: "done".to_string(),
|
||||
following: follow,
|
||||
});
|
||||
}
|
||||
|
||||
// Confirm whether follow state already matches what the user requested
|
||||
if let Some(actual) = check_follow_state_with_fallback(&state.api, &auth, &clean).await {
|
||||
if actual == follow {
|
||||
apply_local_follow_change(&app, &state, &clean, follow).await;
|
||||
return Ok(KickFollowResult {
|
||||
status: "done".to_string(),
|
||||
following: follow,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Kick protects /follow with browser Kasada / CSRF verification (403 / 419 / 429):
|
||||
// Open the real Kick channel page inside the signed-in WebView2 profile and auto-sync
|
||||
// as soon as the user clicks Follow / Unfollow.
|
||||
if matches!(status, 403 | 419 | 429) {
|
||||
if let Some(existing) = app.get_webview_window("kick-follow") {
|
||||
let _ = existing.close();
|
||||
}
|
||||
|
||||
let target_url = format!("https://kick.com/{}", clean)
|
||||
.parse()
|
||||
.map_err(|_| AppError::InvalidInput("Kick kanal adresi geçersiz".to_string()))?;
|
||||
|
||||
let window = WebviewWindowBuilder::new(&app, "kick-follow", WebviewUrl::External(target_url))
|
||||
.title(&format!("Kick · {} - Takip Et", clean))
|
||||
.inner_size(980.0, 720.0)
|
||||
.center()
|
||||
.resizable(true)
|
||||
.focused(true)
|
||||
.build()
|
||||
.map_err(|err| AppError::General(format!("Kick takip penceresi açılamadı: {}", err)))?;
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
|
||||
let watch_app = app.clone();
|
||||
let watch_slug = clean.clone();
|
||||
let fallback_auth = auth.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
for _ in 0..120u32 {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
|
||||
let Some(win) = watch_app.get_webview_window("kick-follow") else {
|
||||
return;
|
||||
};
|
||||
let Some(st) = watch_app.try_state::<AppState>() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut fresh_auth = fallback_auth.clone();
|
||||
if let Ok(kick_url) = "https://kick.com".parse() {
|
||||
if let Ok(cookies) = win.cookies_for_url(kick_url) {
|
||||
let pairs: Vec<(String, String)> = cookies
|
||||
.iter()
|
||||
.map(|c| (c.name().to_string(), c.value().to_string()))
|
||||
.collect();
|
||||
if let Some(raw_tok) = find_cookie(&pairs, "session_token") {
|
||||
let norm = normalize_session_token(raw_tok);
|
||||
if !norm.is_empty() {
|
||||
fresh_auth.token = norm;
|
||||
}
|
||||
}
|
||||
let chdr = cookie_header(&pairs);
|
||||
if !chdr.is_empty() {
|
||||
fresh_auth.cookie_header = chdr;
|
||||
}
|
||||
if let Some(xsrf) = find_cookie(&pairs, "XSRF-TOKEN") {
|
||||
fresh_auth.xsrf_token = percent_decode(xsrf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if check_follow_state_with_fallback(&st.api, &fresh_auth, &watch_slug).await
|
||||
== Some(follow)
|
||||
{
|
||||
let snapshot = {
|
||||
let mut cfg = st.config.write().await;
|
||||
if !fresh_auth.token.is_empty() {
|
||||
cfg.kick_token = fresh_auth.token;
|
||||
}
|
||||
if !fresh_auth.cookie_header.is_empty() {
|
||||
cfg.kick_cookies = fresh_auth.cookie_header;
|
||||
}
|
||||
if !fresh_auth.xsrf_token.is_empty() {
|
||||
cfg.kick_xsrf = fresh_auth.xsrf_token;
|
||||
}
|
||||
cfg.clone()
|
||||
};
|
||||
let _ = st.config_service.save(&snapshot);
|
||||
apply_local_follow_change(&watch_app, &st, &watch_slug, follow).await;
|
||||
if let Some(w) = watch_app.get_webview_window("kick-follow") {
|
||||
let _ = w.close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return Ok(KickFollowResult {
|
||||
status: "window_opened".to_string(),
|
||||
following: !follow,
|
||||
});
|
||||
}
|
||||
|
||||
let detail = serde_json::from_str::<serde_json::Value>(&response_body)
|
||||
.ok()
|
||||
.and_then(|value| {
|
||||
value
|
||||
.get("message")
|
||||
.or_else(|| value.get("error"))
|
||||
.and_then(|field| field.as_str())
|
||||
.map(|text| text.to_string())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
Err(AppError::General(if detail.is_empty() {
|
||||
format!("Takip isteği başarısız (HTTP {})", status)
|
||||
} else {
|
||||
format!("Takip isteği başarısız: {}", detail)
|
||||
}))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn kick_follow_state(
|
||||
channel_slug: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<bool, AppError> {
|
||||
let cfg = state.config.read().await.clone();
|
||||
if cfg.kick_token.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let clean = crate::commands::channel::clean_channel_name(&channel_slug);
|
||||
if clean.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let auth = auth_context(&cfg);
|
||||
if let Some(following) = check_follow_state_with_fallback(&state.api, &auth, &clean).await {
|
||||
return Ok(following);
|
||||
}
|
||||
|
||||
Ok(cfg
|
||||
.favorites
|
||||
.iter()
|
||||
.any(|f| crate::commands::channel::clean_channel_name(f) == clean))
|
||||
}
|
||||
|
||||
/// Downloads an emote image through curl and returns a `data:` URL so the
|
||||
/// chat can always render it, even if the WebView blocks files.kick.com.
|
||||
#[tauri::command]
|
||||
pub async fn fetch_emote_image(emote_id: String) -> Result<String, AppError> {
|
||||
let id: String = emote_id.chars().filter(|c| c.is_ascii_digit()).collect();
|
||||
if id.is_empty() || id.len() > 12 {
|
||||
return Err(AppError::InvalidInput("Geçersiz emote kimliği".to_string()));
|
||||
}
|
||||
|
||||
if let Ok(cache) = EMOTE_IMAGE_CACHE.lock() {
|
||||
if let Some(cached) = cache.get(&id) {
|
||||
return Ok(cached.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let url = format!("https://files.kick.com/emotes/{}/fullsize", id);
|
||||
let mut command = tokio::process::Command::new(crate::services::kick_api::curl_binary());
|
||||
command.args([
|
||||
"-sS",
|
||||
"-L",
|
||||
"--max-time",
|
||||
"20",
|
||||
"--max-filesize",
|
||||
"2097152",
|
||||
"-A",
|
||||
"Mozilla/5.0",
|
||||
&url,
|
||||
]);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
let output = command.output().await.map_err(AppError::Io)?;
|
||||
let bytes = output.stdout;
|
||||
if !output.status.success() || bytes.is_empty() {
|
||||
return Err(AppError::General(
|
||||
"Emote görseli indirilemedi".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let mime = if bytes.starts_with(b"GIF8") {
|
||||
"image/gif"
|
||||
} else if bytes.starts_with(&[0x89, b'P', b'N', b'G']) {
|
||||
"image/png"
|
||||
} else if bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
"image/jpeg"
|
||||
} else {
|
||||
"image/webp"
|
||||
};
|
||||
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
|
||||
let data_url = format!("data:{};base64,{}", mime, encoded);
|
||||
|
||||
if let Ok(mut cache) = EMOTE_IMAGE_CACHE.lock() {
|
||||
if cache.len() > 400 {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(id, data_url.clone());
|
||||
}
|
||||
|
||||
Ok(data_url)
|
||||
}
|
||||
|
||||
/// Formats `:emote:` shortcuts with the channel emote map before sending.
|
||||
#[tauri::command]
|
||||
pub fn kick_format_message(
|
||||
content: String,
|
||||
emotes: Vec<KickEmote>,
|
||||
) -> Result<String, AppError> {
|
||||
let map: Vec<(String, String)> = emotes
|
||||
.into_iter()
|
||||
.map(|emote| (emote.name, emote.id))
|
||||
.collect();
|
||||
Ok(format_emotes(&content, &map))
|
||||
}
|
||||
11
src-tauri/src/commands/mod.rs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
pub mod channel;
|
||||
pub mod chat;
|
||||
pub mod config;
|
||||
pub mod kick;
|
||||
pub mod player;
|
||||
|
||||
pub use channel::*;
|
||||
pub use chat::*;
|
||||
pub use config::*;
|
||||
pub use kick::*;
|
||||
pub use player::*;
|
||||
401
src-tauri/src/commands/player.rs
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
use crate::error::AppError;
|
||||
use crate::services::{HlsVariant, MpvState};
|
||||
use crate::state::AppState;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tauri::{Emitter, State};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct InstalledPlayerInfo {
|
||||
pub name: String,
|
||||
pub path: Option<String>,
|
||||
pub available: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StreamPlaybackInfo {
|
||||
pub channel_name: String,
|
||||
pub is_live: bool,
|
||||
pub playback_url: Option<String>,
|
||||
pub embed_url: String,
|
||||
pub player_mode: String,
|
||||
pub player_type: String,
|
||||
pub title: String,
|
||||
pub viewers: i64,
|
||||
pub started_at: Option<String>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn detect_installed_players(
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Vec<InstalledPlayerInfo>, AppError> {
|
||||
let cfg = state.config.read().await;
|
||||
|
||||
let vlc_path = state.player.find_vlc(Some(&cfg.vlc_path));
|
||||
let mpv_path = state.player.find_mpv(Some(&cfg.mpv_path));
|
||||
let streamlink_path = state.player.find_streamlink(Some(&cfg.streamlink_path));
|
||||
|
||||
Ok(vec![
|
||||
InstalledPlayerInfo {
|
||||
name: "Internal Native Player (libmpv D3D11VA)".to_string(),
|
||||
path: None,
|
||||
available: true,
|
||||
},
|
||||
InstalledPlayerInfo {
|
||||
name: "VLC Media Player".to_string(),
|
||||
available: vlc_path.is_some(),
|
||||
path: vlc_path,
|
||||
},
|
||||
InstalledPlayerInfo {
|
||||
name: "MPV Player".to_string(),
|
||||
available: mpv_path.is_some(),
|
||||
path: mpv_path,
|
||||
},
|
||||
InstalledPlayerInfo {
|
||||
name: "Streamlink".to_string(),
|
||||
available: streamlink_path.is_some(),
|
||||
path: streamlink_path,
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn play_stream(
|
||||
channel_name: String,
|
||||
quality: Option<String>,
|
||||
force_external: Option<bool>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<StreamPlaybackInfo, AppError> {
|
||||
let clean = channel_name
|
||||
.trim()
|
||||
.trim_start_matches('@')
|
||||
.trim_start_matches("https://kick.com/")
|
||||
.trim_start_matches("http://kick.com/")
|
||||
.trim_start_matches("kick.com/")
|
||||
.trim_end_matches('/')
|
||||
.to_lowercase();
|
||||
|
||||
if clean.is_empty() {
|
||||
return Err(AppError::InvalidInput("Kanal adı belirtilmedi".to_string()));
|
||||
}
|
||||
|
||||
let channel_data = state.api.get_channel(&clean).await?;
|
||||
let is_live = channel_data.livestream.is_some();
|
||||
let playback_url = channel_data.playback_url.clone();
|
||||
let started_at = channel_data
|
||||
.livestream
|
||||
.as_ref()
|
||||
.and_then(|l| l.normalized_started_at());
|
||||
let title = channel_data
|
||||
.livestream
|
||||
.as_ref()
|
||||
.and_then(|l| l.session_title.clone())
|
||||
.unwrap_or_default();
|
||||
let viewers = channel_data
|
||||
.livestream
|
||||
.as_ref()
|
||||
.and_then(|l| l.viewer_count)
|
||||
.unwrap_or(0);
|
||||
|
||||
let (player_type, vlc_path, mpv_path, streamlink_path, preferred_quality, extra_args) = {
|
||||
let cfg = state.config.read().await;
|
||||
(
|
||||
cfg.player_type.clone(),
|
||||
cfg.vlc_path.clone(),
|
||||
cfg.mpv_path.clone(),
|
||||
cfg.streamlink_path.clone(),
|
||||
cfg.default_quality.clone(),
|
||||
cfg.custom_player_args.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
let target_quality = quality.unwrap_or(preferred_quality);
|
||||
let use_external = force_external.unwrap_or(player_type.to_lowercase() != "internal");
|
||||
|
||||
let embed_url = format!("https://player.kick.com/{}", clean);
|
||||
|
||||
if use_external {
|
||||
let raw_url = playback_url.as_deref().unwrap_or(&embed_url);
|
||||
let resolved_url = state
|
||||
.api
|
||||
.resolve_quality_url(raw_url, &target_quality)
|
||||
.await;
|
||||
|
||||
let player_path = match player_type.to_lowercase().as_str() {
|
||||
"mpv" => Some(mpv_path.as_str()),
|
||||
_ => Some(vlc_path.as_str()),
|
||||
};
|
||||
|
||||
state
|
||||
.player
|
||||
.play_external(crate::services::ExternalPlayerOptions {
|
||||
channel_name: &clean,
|
||||
player_type: &player_type,
|
||||
stream_url: &resolved_url,
|
||||
player_path,
|
||||
streamlink_path: Some(&streamlink_path),
|
||||
quality: &target_quality,
|
||||
extra_args: Some(&extra_args),
|
||||
})?;
|
||||
}
|
||||
|
||||
{
|
||||
let mut active = state.active_stream.write().await;
|
||||
*active = Some(clean.clone());
|
||||
}
|
||||
|
||||
let info = StreamPlaybackInfo {
|
||||
channel_name: clean.clone(),
|
||||
is_live,
|
||||
playback_url,
|
||||
embed_url,
|
||||
player_mode: if use_external {
|
||||
"external".to_string()
|
||||
} else {
|
||||
"internal".to_string()
|
||||
},
|
||||
player_type,
|
||||
title,
|
||||
viewers,
|
||||
started_at,
|
||||
};
|
||||
|
||||
let _ = state.app_handle.emit("stream-playback-changed", &info);
|
||||
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_hls_variants(
|
||||
master_url: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Vec<HlsVariant>, AppError> {
|
||||
state.api.get_hls_variants(&master_url).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_load_stream(
|
||||
url: String,
|
||||
headers: Option<HashMap<String, String>>,
|
||||
slot_id: Option<String>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
let url_clone = url;
|
||||
let headers_clone = headers;
|
||||
let slot_clone = slot_id;
|
||||
let mpv_inner = Arc::clone(mpv.inner());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
mpv_inner.load_stream(&url_clone, headers_clone.as_ref(), slot_clone.as_deref())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| AppError::General(format!("mpv load_stream görev hatası: {}", e)))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_set_bounds(
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
scale_factor: f64,
|
||||
slot_id: Option<String>,
|
||||
above_parent: Option<bool>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.set_bounds(
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
scale_factor,
|
||||
slot_id.as_deref(),
|
||||
above_parent,
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_set_visible(
|
||||
visible: bool,
|
||||
slot_id: Option<String>,
|
||||
above_parent: Option<bool>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.set_visible(visible, slot_id.as_deref(), above_parent)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_set_pause(
|
||||
paused: bool,
|
||||
slot_id: Option<String>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.set_pause(paused, slot_id.as_deref())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_set_volume(
|
||||
volume: f64,
|
||||
slot_id: Option<String>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.set_volume(volume, slot_id.as_deref())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_set_mute(
|
||||
muted: bool,
|
||||
slot_id: Option<String>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.set_mute(muted, slot_id.as_deref())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_seek_live(
|
||||
slot_id: Option<String>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.seek_live(slot_id.as_deref())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_seek_relative(
|
||||
delta_secs: f64,
|
||||
slot_id: Option<String>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.seek_relative(delta_secs, slot_id.as_deref())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_seek_behind_live(
|
||||
behind_secs: f64,
|
||||
slot_id: Option<String>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.seek_behind_live(behind_secs, slot_id.as_deref())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_load_vod_dvr(
|
||||
channel_name: String,
|
||||
target_secs: f64,
|
||||
preferred_height: Option<u32>,
|
||||
slot_id: Option<String>,
|
||||
state: State<'_, AppState>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
let dvr = state
|
||||
.api
|
||||
.get_live_dvr_source(&channel_name, preferred_height)
|
||||
.await?;
|
||||
let mpv_inner = Arc::clone(mpv.inner());
|
||||
let slot_clone = slot_id;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
mpv_inner.load_vod_dvr(
|
||||
&dvr.playlist_url,
|
||||
target_secs,
|
||||
dvr.total_secs_hint,
|
||||
slot_clone.as_deref(),
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| AppError::General(format!("mpv load_vod_dvr görev hatası: {}", e)))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_update_live_url(
|
||||
url: String,
|
||||
slot_id: Option<String>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.update_live_url(&url, slot_id.as_deref())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_stop(
|
||||
slot_id: Option<String>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
mpv.stop(slot_id.as_deref())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mpv_stop_all(mpv: State<'_, Arc<MpvState>>) -> Result<(), AppError> {
|
||||
mpv.stop_all();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn stop_stream(
|
||||
channel_name: Option<String>,
|
||||
state: State<'_, AppState>,
|
||||
mpv: State<'_, Arc<MpvState>>,
|
||||
) -> Result<(), AppError> {
|
||||
if let Some(name) = channel_name {
|
||||
let clean = name.trim().to_lowercase();
|
||||
state.player.stop(&clean);
|
||||
let _ = mpv.stop(Some("main"));
|
||||
let _ = mpv.set_visible(false, Some("main"), Some(false));
|
||||
|
||||
let mut active = state.active_stream.write().await;
|
||||
if active.as_deref() == Some(&clean) {
|
||||
*active = None;
|
||||
}
|
||||
} else {
|
||||
state.player.stop_all();
|
||||
mpv.stop_all();
|
||||
let mut active = state.active_stream.write().await;
|
||||
*active = None;
|
||||
}
|
||||
|
||||
let _ = state.app_handle.emit("stream-stopped", ());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_stream_info(
|
||||
channel_name: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<StreamPlaybackInfo, AppError> {
|
||||
let clean = channel_name.trim().to_lowercase();
|
||||
let channel_data = state.api.get_channel(&clean).await?;
|
||||
let is_live = channel_data.livestream.is_some();
|
||||
let playback_url = channel_data.playback_url.clone();
|
||||
let started_at = channel_data
|
||||
.livestream
|
||||
.as_ref()
|
||||
.and_then(|l| l.normalized_started_at());
|
||||
let title = channel_data
|
||||
.livestream
|
||||
.as_ref()
|
||||
.and_then(|l| l.session_title.clone())
|
||||
.unwrap_or_default();
|
||||
let viewers = channel_data
|
||||
.livestream
|
||||
.as_ref()
|
||||
.and_then(|l| l.viewer_count)
|
||||
.unwrap_or(0);
|
||||
|
||||
let player_type = {
|
||||
let cfg = state.config.read().await;
|
||||
cfg.player_type.clone()
|
||||
};
|
||||
|
||||
Ok(StreamPlaybackInfo {
|
||||
channel_name: clean.clone(),
|
||||
is_live,
|
||||
playback_url,
|
||||
embed_url: format!("https://player.kick.com/{}", clean),
|
||||
player_mode: if player_type.to_lowercase() == "internal" {
|
||||
"internal".to_string()
|
||||
} else {
|
||||
"external".to_string()
|
||||
},
|
||||
player_type,
|
||||
title,
|
||||
viewers,
|
||||
started_at,
|
||||
})
|
||||
}
|
||||
44
src-tauri/src/error.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
use serde::Serialize;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AppError {
|
||||
#[error("Ağ hatası: {0}")]
|
||||
Network(#[from] reqwest::Error),
|
||||
|
||||
#[error("JSON serileştirme hatası: {0}")]
|
||||
Serialization(#[from] serde_json::Error),
|
||||
|
||||
#[error("Dosya G/Ç hatası: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
#[error("WebSocket hatası: {0}")]
|
||||
WebSocket(String),
|
||||
|
||||
#[error("Kanal bulunamadı: {0}")]
|
||||
ChannelNotFound(String),
|
||||
|
||||
#[error("Oynatıcı bulunamadı: {0}")]
|
||||
PlayerNotFound(String),
|
||||
|
||||
#[error("Geçersiz işlem veya parametre: {0}")]
|
||||
InvalidInput(String),
|
||||
|
||||
#[error("Ses çalma hatası: {0}")]
|
||||
Audio(String),
|
||||
|
||||
#[error("Yayın akışına erişilemedi: {0}")]
|
||||
StreamUnavailable(String),
|
||||
|
||||
#[error("Bilinmeyen sistem hatası: {0}")]
|
||||
General(String),
|
||||
}
|
||||
|
||||
impl Serialize for AppError {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.to_string())
|
||||
}
|
||||
}
|
||||
344
src-tauri/src/lib.rs
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
pub mod commands;
|
||||
pub mod error;
|
||||
pub mod models;
|
||||
pub mod services;
|
||||
pub mod state;
|
||||
|
||||
use services::{AppLogger, MpvState, ShortcutService};
|
||||
use state::AppState;
|
||||
use std::sync::Arc;
|
||||
use tauri::menu::{CheckMenuItem, Menu, MenuItem};
|
||||
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
|
||||
use tauri::{AppHandle, Emitter, LogicalPosition, LogicalSize, Manager, WindowEvent};
|
||||
|
||||
fn show_main_window(app: &AppHandle) {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.unminimize();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
if let Some(mpv) = app.try_state::<Arc<MpvState>>() {
|
||||
mpv.on_window_restored();
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo tauri dev` runs the binary from a `debug` target directory; shortcut
|
||||
/// repair must never point a real user shortcut at that throwaway build.
|
||||
fn is_dev_executable() -> bool {
|
||||
std::env::current_exe()
|
||||
.map(|path| {
|
||||
let lowered = path.to_string_lossy().to_lowercase();
|
||||
lowered.contains("\\debug\\") || lowered.contains("/debug/")
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Persists the window geometry so the next launch reopens exactly where the
|
||||
/// user left it (maximized state is remembered separately).
|
||||
fn persist_window_state(window: &tauri::WebviewWindow, state: &AppState) {
|
||||
let is_maximized = window.is_maximized().unwrap_or(false);
|
||||
let scale = window.scale_factor().unwrap_or(1.0);
|
||||
let size = window
|
||||
.inner_size()
|
||||
.ok()
|
||||
.map(|size| size.to_logical::<u32>(scale));
|
||||
let position = window
|
||||
.outer_position()
|
||||
.ok()
|
||||
.map(|pos| pos.to_logical::<i32>(scale));
|
||||
|
||||
let snapshot = {
|
||||
let mut cfg = state.config.blocking_write();
|
||||
cfg.window_maximized = is_maximized;
|
||||
if !is_maximized {
|
||||
if let Some(size) = size {
|
||||
cfg.window_width = size.width.max(820);
|
||||
cfg.window_height = size.height.max(560);
|
||||
}
|
||||
if let Some(position) = position {
|
||||
cfg.window_x = Some(position.x);
|
||||
cfg.window_y = Some(position.y);
|
||||
}
|
||||
}
|
||||
cfg.clone()
|
||||
};
|
||||
|
||||
if let Err(err) = state.config_service.save(&snapshot) {
|
||||
log::warn!("Pencere durumu kaydedilemedi: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
// Initialize rotating file logger before any other subsystem
|
||||
let _ = AppLogger::init();
|
||||
|
||||
let builder = tauri::Builder::default()
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
|
||||
show_main_window(app);
|
||||
}))
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::get_channels,
|
||||
commands::add_channel,
|
||||
commands::remove_channel,
|
||||
commands::set_channel_group,
|
||||
commands::refresh_channels,
|
||||
commands::import_channels,
|
||||
commands::export_channels,
|
||||
commands::get_top_tr_channels,
|
||||
commands::get_small_tr_channels,
|
||||
commands::detect_installed_players,
|
||||
commands::play_stream,
|
||||
commands::stop_stream,
|
||||
commands::get_stream_info,
|
||||
commands::get_hls_variants,
|
||||
commands::mpv_load_stream,
|
||||
commands::mpv_set_bounds,
|
||||
commands::mpv_set_visible,
|
||||
commands::mpv_set_pause,
|
||||
commands::mpv_set_volume,
|
||||
commands::mpv_set_mute,
|
||||
commands::mpv_seek_live,
|
||||
commands::mpv_seek_relative,
|
||||
commands::mpv_seek_behind_live,
|
||||
commands::mpv_load_vod_dvr,
|
||||
commands::mpv_update_live_url,
|
||||
commands::mpv_stop,
|
||||
commands::mpv_stop_all,
|
||||
commands::connect_chat,
|
||||
commands::disconnect_chat,
|
||||
commands::get_chat_status,
|
||||
commands::get_config,
|
||||
commands::update_config,
|
||||
commands::play_test_sound,
|
||||
commands::create_desktop_shortcut,
|
||||
commands::open_logs_dir,
|
||||
commands::get_recent_logs,
|
||||
commands::clear_logs,
|
||||
commands::reset_config,
|
||||
commands::kick_open_login,
|
||||
commands::kick_auth_profile,
|
||||
commands::kick_manual_token,
|
||||
commands::kick_logout,
|
||||
commands::kick_sync_followed,
|
||||
commands::kick_send_message,
|
||||
commands::kick_channel_emotes,
|
||||
commands::kick_follow_channel,
|
||||
commands::kick_format_message,
|
||||
commands::kick_follow_state,
|
||||
commands::fetch_emote_image,
|
||||
])
|
||||
.on_window_event(|window, event| match event {
|
||||
WindowEvent::CloseRequested { api, .. } => {
|
||||
let Some(state) = window.try_state::<AppState>() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(webview) = window
|
||||
.app_handle()
|
||||
.get_webview_window(window.label())
|
||||
{
|
||||
persist_window_state(&webview, &state);
|
||||
}
|
||||
|
||||
let should_hide = state
|
||||
.config
|
||||
.try_read()
|
||||
.map(|cfg| cfg.minimize_to_tray)
|
||||
.unwrap_or(false);
|
||||
|
||||
if should_hide {
|
||||
api.prevent_close();
|
||||
if let Some(mpv) = window.try_state::<Arc<MpvState>>() {
|
||||
mpv.on_window_minimized_or_hidden();
|
||||
}
|
||||
let _ = window.hide();
|
||||
} else {
|
||||
state.player.stop_all();
|
||||
if let Some(mpv) = window.try_state::<Arc<MpvState>>() {
|
||||
mpv.shutdown_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::Moved(_) => {
|
||||
if window.label() == "main" {
|
||||
if let Some(mpv) = window.try_state::<Arc<MpvState>>() {
|
||||
mpv.on_window_moved();
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::Resized(size) => {
|
||||
if window.label() != "main" {
|
||||
return;
|
||||
}
|
||||
if let Some(mpv) = window.try_state::<Arc<MpvState>>() {
|
||||
if size.width == 0 || size.height == 0 {
|
||||
mpv.on_window_minimized_or_hidden();
|
||||
} else {
|
||||
mpv.on_window_restored();
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::Focused(true) => {
|
||||
if window.label() == "main" {
|
||||
if let Some(mpv) = window.try_state::<Arc<MpvState>>() {
|
||||
mpv.ensure_z_order();
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||
if window.label() == "main" {
|
||||
let _ = window.emit("window-dpi-changed", *scale_factor);
|
||||
if let Some(mpv) = window.try_state::<Arc<MpvState>>() {
|
||||
mpv.on_window_moved();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.setup(|app| {
|
||||
let app_handle = app.handle().clone();
|
||||
let app_state = AppState::new(app_handle.clone())?;
|
||||
|
||||
app_state.polling.start();
|
||||
app.manage(app_state);
|
||||
let mpv_state = Arc::new(MpvState::new(app_handle));
|
||||
app.manage(Arc::clone(&mpv_state));
|
||||
|
||||
// Restore last window geometry / maximized state & enforce transparent WebView2 surface
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.set_background_color(Some(tauri::window::Color(0, 0, 0, 0)));
|
||||
mpv_state.attach_main_window(&window);
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
let cfg = state.config.blocking_read();
|
||||
let width = cfg.window_width.max(820);
|
||||
let height = cfg.window_height.max(560);
|
||||
let position = cfg.window_x.zip(cfg.window_y);
|
||||
let maximized = cfg.window_maximized;
|
||||
drop(cfg);
|
||||
|
||||
let _ = window.set_size(LogicalSize::new(width, height));
|
||||
if let Some((x, y)) = position {
|
||||
let _ = window.set_position(LogicalPosition::new(x, y));
|
||||
}
|
||||
if maximized {
|
||||
let _ = window.maximize();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Repair stale Desktop / Start Menu shortcuts from older installs.
|
||||
// Never in dev builds: the debug executable must not hijack user shortcuts.
|
||||
if !is_dev_executable() {
|
||||
if let Err(err) = ShortcutService::repair_shortcuts() {
|
||||
log::warn!("Kısayol onarımı atlandı: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
let notifications_enabled = app
|
||||
.try_state::<AppState>()
|
||||
.and_then(|state| state.config.try_read().ok().map(|cfg| cfg.notifications_enabled))
|
||||
.unwrap_or(true);
|
||||
|
||||
let show_item =
|
||||
MenuItem::with_id(app, "show", "Uygulamayı Göster", true, None::<&str>)?;
|
||||
let notifications_item = CheckMenuItem::with_id(
|
||||
app,
|
||||
"toggle-notifications",
|
||||
"Bildirimleri Sessize Al",
|
||||
true,
|
||||
!notifications_enabled,
|
||||
None::<&str>,
|
||||
)?;
|
||||
let quit_item = MenuItem::with_id(app, "quit", "Çıkış", true, None::<&str>)?;
|
||||
let tray_menu = Menu::with_items(app, &[&show_item, ¬ifications_item, &quit_item])?;
|
||||
|
||||
let notifications_handle = notifications_item.clone();
|
||||
let mut tray_builder = TrayIconBuilder::with_id("main-tray")
|
||||
.tooltip("LD KickWatch")
|
||||
.menu(&tray_menu)
|
||||
.show_menu_on_left_click(false)
|
||||
.on_menu_event(move |app, event| match event.id.as_ref() {
|
||||
"show" => show_main_window(app),
|
||||
"toggle-notifications" => {
|
||||
let Some(state) = app.try_state::<AppState>() else {
|
||||
return;
|
||||
};
|
||||
let (enabled, snapshot) = {
|
||||
let mut cfg = state.config.blocking_write();
|
||||
cfg.notifications_enabled = !cfg.notifications_enabled;
|
||||
(cfg.notifications_enabled, cfg.clone())
|
||||
};
|
||||
let _ = notifications_handle.set_checked(!enabled);
|
||||
if let Err(err) = state.config_service.save(&snapshot) {
|
||||
log::warn!("Bildirim ayarı kaydedilemedi: {}", err);
|
||||
}
|
||||
let _ = app.emit("notifications-changed", enabled);
|
||||
}
|
||||
"quit" => {
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
persist_window_state(&window, &state);
|
||||
}
|
||||
state.player.stop_all();
|
||||
}
|
||||
if let Some(mpv) = app.try_state::<Arc<MpvState>>() {
|
||||
mpv.shutdown_all();
|
||||
}
|
||||
log::info!("Uygulama tepsi menüsünden kapatıldı.");
|
||||
app.exit(0);
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.on_tray_icon_event(|tray, event| {
|
||||
if let TrayIconEvent::Click {
|
||||
button: MouseButton::Left,
|
||||
button_state: MouseButtonState::Up,
|
||||
..
|
||||
} = event
|
||||
{
|
||||
show_main_window(tray.app_handle());
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(icon) = app.default_window_icon() {
|
||||
tray_builder = tray_builder.icon(icon.clone());
|
||||
}
|
||||
tray_builder.build(app)?;
|
||||
|
||||
log::info!("LD KickWatch backend ve tüm servisler başarıyla başlatıldı.");
|
||||
Ok(())
|
||||
});
|
||||
|
||||
let app = match builder.build(tauri::generate_context!()) {
|
||||
Ok(app) => app,
|
||||
Err(err) => {
|
||||
log::error!("LD KickWatch başlatılamadı: {}", err);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
app.run(|app_handle, event| {
|
||||
if matches!(
|
||||
event,
|
||||
tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit
|
||||
) {
|
||||
if let (Some(window), Some(state)) = (
|
||||
app_handle.get_webview_window("main"),
|
||||
app_handle.try_state::<AppState>(),
|
||||
) {
|
||||
persist_window_state(&window, &state);
|
||||
state.player.stop_all();
|
||||
}
|
||||
if let Some(mpv) = app_handle.try_state::<Arc<MpvState>>() {
|
||||
mpv.shutdown_all();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
719
src-tauri/src/main.rs
Normal file
|
|
@ -0,0 +1,719 @@
|
|||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
ld_kickwatch_lib::run();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use ld_kickwatch_lib::commands::channel::clean_channel_name;
|
||||
use ld_kickwatch_lib::models::config::AppConfig;
|
||||
use ld_kickwatch_lib::models::kick_api::KickChannelResponse;
|
||||
use ld_kickwatch_lib::models::{ChannelCard, ChatMessage};
|
||||
use ld_kickwatch_lib::services::hls_pipe::{
|
||||
canonical_segment_key, collect_new_segments, parse_media_playlist,
|
||||
select_initial_segments, PipeMode, SeenTracker,
|
||||
};
|
||||
use ld_kickwatch_lib::services::kick_api::{
|
||||
filter_small_tr_livestreams, normalize_kick_utc_timestamp, parse_followed_page,
|
||||
parse_hls_variants, parse_live_dvr_video_source, parse_top_tr_livestreams,
|
||||
validate_stream_url as validate_media_url, KickApiService,
|
||||
};
|
||||
use ld_kickwatch_lib::services::mpv_player::{run_live_smoke_test, sanitize_http_headers};
|
||||
use ld_kickwatch_lib::services::player::{
|
||||
sanitize_extra_args, validate_channel_name, validate_stream_url,
|
||||
};
|
||||
use ld_kickwatch_lib::services::chat::badges_from_sender;
|
||||
use ld_kickwatch_lib::services::kick_auth::{format_emotes, normalize_session_token};
|
||||
use ld_kickwatch_lib::services::sound::SoundService;
|
||||
|
||||
#[test]
|
||||
fn test_sound_wav_riff() {
|
||||
let wav = SoundService::generate_chime_wav(587.33, 880.0, 260);
|
||||
assert!(wav.len() > 44);
|
||||
assert_eq!(&wav[0..4], b"RIFF");
|
||||
assert_eq!(&wav[8..12], b"WAVE");
|
||||
assert_eq!(&wav[12..16], b"fmt ");
|
||||
assert_eq!(&wav[36..40], b"data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_app_config() {
|
||||
let cfg = AppConfig::default();
|
||||
assert!(!cfg.favorites.is_empty());
|
||||
assert!(cfg.auto_update_on_startup);
|
||||
assert_eq!(cfg.refresh_interval_seconds, 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_channel_name_validation() {
|
||||
assert!(validate_channel_name("valid_streamer-123").is_ok());
|
||||
assert!(validate_channel_name("").is_err());
|
||||
assert!(validate_channel_name("streamer;calc.exe").is_err());
|
||||
assert!(validate_channel_name("streamer&evil").is_err());
|
||||
assert!(validate_channel_name("streamer/test").is_err());
|
||||
assert!(validate_channel_name("streamer\"injection").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stream_url_validation() {
|
||||
assert!(validate_stream_url("https://stream.kick.com/live/master.m3u8").is_ok());
|
||||
assert!(validate_stream_url("http://stream.kick.com/live/master.m3u8").is_ok());
|
||||
assert!(validate_stream_url("--input-slave=calc").is_err());
|
||||
assert!(validate_stream_url("file:///etc/passwd").is_err());
|
||||
assert!(validate_stream_url("https://example.com/stream\nevil").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sanitize_extra_args() {
|
||||
let raw = "--network-caching=1000 --exec=cmd.exe --hwdec=auto --input-ipc-server=\\\\.\\pipe\\x --log-file=out.txt --stream-record=rec.ts -o=out.mp4 --sout=#std ;rmdir /s /q";
|
||||
let sanitized = sanitize_extra_args(raw);
|
||||
assert!(sanitized.contains(&"--network-caching=1000".to_string()));
|
||||
assert!(sanitized.contains(&"--hwdec=auto".to_string()));
|
||||
assert!(!sanitized.iter().any(|a| a.contains("--exec")));
|
||||
assert!(!sanitized.iter().any(|a| a.contains("cmd.exe")));
|
||||
assert!(!sanitized.iter().any(|a| a.contains("--input-ipc-server")));
|
||||
assert!(!sanitized.iter().any(|a| a.contains("--log-file")));
|
||||
assert!(!sanitized.iter().any(|a| a.contains("--stream-record")));
|
||||
assert!(!sanitized.iter().any(|a| a.contains("-o=")));
|
||||
assert!(!sanitized.iter().any(|a| a.contains("--sout")));
|
||||
assert!(!sanitized.iter().any(|a| a.contains(";")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clean_channel_name() {
|
||||
assert_eq!(clean_channel_name("@StreamerName"), "streamername");
|
||||
assert_eq!(clean_channel_name("https://kick.com/Streamer/"), "streamer");
|
||||
assert_eq!(clean_channel_name(" kick.com/streamer "), "streamer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_media_bridge_rejects_local_targets() {
|
||||
assert!(validate_media_url("file:///C:/Windows/win.ini").is_err());
|
||||
assert!(validate_media_url("http://localhost:8080/live.m3u8").is_err());
|
||||
assert!(validate_media_url("http://127.0.0.1/live.m3u8").is_err());
|
||||
assert!(validate_media_url("http://192.168.1.20/live.m3u8").is_err());
|
||||
assert!(validate_media_url("http://169.254.169.254/latest/meta-data").is_err());
|
||||
assert!(validate_media_url("https://[::1]/live.m3u8").is_err());
|
||||
assert!(validate_media_url("not a url").is_err());
|
||||
assert!(validate_media_url("https://kick.com/api/v2/channels/x").is_ok());
|
||||
}
|
||||
|
||||
/// Live network check: pulls a real Kick manifest and variant playlist
|
||||
/// through the Rust bridge (the path that bypasses the CDN's CORS rules).
|
||||
/// Run manually with: cargo test -- --ignored
|
||||
#[tokio::test]
|
||||
#[ignore = "requires network access to kick.com"]
|
||||
async fn test_media_bridge_fetches_live_stream() {
|
||||
let service = KickApiService::new().expect("KickApiService");
|
||||
let feed = std::process::Command::new("curl")
|
||||
.args([
|
||||
"-sS",
|
||||
"--max-time",
|
||||
"15",
|
||||
"-H",
|
||||
"Accept: application/json",
|
||||
"https://kick.com/stream/livestreams/en?page=1&limit=3",
|
||||
])
|
||||
.output()
|
||||
.expect("curl feed");
|
||||
let feed = String::from_utf8(feed.stdout).expect("utf8 feed");
|
||||
let feed_json: serde_json::Value = serde_json::from_str(&feed).expect("feed json");
|
||||
let slug = feed_json["data"][0]["channel"]["slug"]
|
||||
.as_str()
|
||||
.expect("live channel slug")
|
||||
.to_string();
|
||||
|
||||
let channel = service.get_channel(&slug).await.expect("channel info");
|
||||
let playback_url = channel.playback_url.expect("playback url");
|
||||
|
||||
let manifest = service
|
||||
.fetch_stream_bytes(&playback_url, None, None)
|
||||
.await
|
||||
.expect("manifest bytes");
|
||||
let manifest_text = String::from_utf8_lossy(&manifest);
|
||||
assert!(
|
||||
manifest_text.starts_with("#EXTM3U"),
|
||||
"unexpected manifest: {manifest_text}"
|
||||
);
|
||||
|
||||
let variant_line = manifest_text
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|line| !line.is_empty() && !line.starts_with('#'))
|
||||
.expect("variant playlist entry")
|
||||
.to_string();
|
||||
let variant_url = reqwest::Url::parse(&playback_url)
|
||||
.expect("base url")
|
||||
.join(&variant_line)
|
||||
.expect("variant url");
|
||||
|
||||
let variant = service
|
||||
.fetch_stream_bytes(variant_url.as_str(), None, None)
|
||||
.await
|
||||
.expect("variant bytes");
|
||||
assert!(
|
||||
String::from_utf8_lossy(&variant).contains("#EXTINF"),
|
||||
"variant playlist has no segments"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_session_token_decoding() {
|
||||
// Kick stores the bearer token URL-encoded; pipes must be restored.
|
||||
assert_eq!(
|
||||
normalize_session_token("%7Cabc%7Cdef%2Bghi%3D"),
|
||||
"|abc|def+ghi="
|
||||
);
|
||||
assert_eq!(normalize_session_token("Bearer 12345%7Ctoken"), "12345|token");
|
||||
assert_eq!(normalize_session_token(" 12345|token "), "12345|token");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_emote_wire_format() {
|
||||
let emotes = vec![
|
||||
("KEKW".to_string(), "KEKW".to_string()),
|
||||
("catJAM".to_string(), "catJAM".to_string()),
|
||||
];
|
||||
assert_eq!(
|
||||
format_emotes("hi :kekw: there", &emotes),
|
||||
"hi [emote:KEKW:KEKW] there"
|
||||
);
|
||||
assert_eq!(format_emotes("plain", &emotes), "plain");
|
||||
assert_eq!(format_emotes(":unknown:", &emotes), ":unknown:");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_chat_badges_parsing() {
|
||||
let payload: serde_json::Value = serde_json::from_str(
|
||||
r#"{"identity":{"badges":[{"type":"moderator","text":"Moderator","active":true},{"type":"subscriber","text":"Subscriber","count":6,"active":true}]}}"#,
|
||||
)
|
||||
.expect("payload");
|
||||
let badges = badges_from_sender(Some(&payload));
|
||||
assert_eq!(badges.len(), 2);
|
||||
assert_eq!(badges[0].badge_type, "moderator");
|
||||
assert_eq!(badges[1].count, Some(6));
|
||||
|
||||
let legacy: serde_json::Value =
|
||||
serde_json::from_str(r#"{"badges":[{"type":"vip","text":"VIP"}]}"#).expect("legacy");
|
||||
assert_eq!(badges_from_sender(Some(&legacy)).len(), 1);
|
||||
assert!(badges_from_sender(None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_hls_variants_sorting_and_urls() {
|
||||
let master = "https://cdn.example.com/hls/v1/master.m3u8?token=abc";
|
||||
let playlist = r#"#EXTM3U
|
||||
#EXT-X-STREAM-INF:BANDWIDTH=1200000,RESOLUTION=852x480,FRAME-RATE=30.000
|
||||
480p30/playlist.m3u8
|
||||
#EXT-X-STREAM-INF:BANDWIDTH=6500000,RESOLUTION=1920x1080,FRAME-RATE=60.000
|
||||
https://edge.example.com/1080p60/index.m3u8
|
||||
#EXT-X-STREAM-INF:BANDWIDTH=3500000,RESOLUTION=1280x720,FRAME-RATE=60.000
|
||||
720p60/index.m3u8
|
||||
"#;
|
||||
let variants = parse_hls_variants(master, playlist);
|
||||
assert_eq!(variants.len(), 3);
|
||||
assert_eq!(variants[0].label, "1080p60");
|
||||
assert_eq!(variants[0].url, "https://edge.example.com/1080p60/index.m3u8");
|
||||
assert_eq!(variants[1].label, "720p60");
|
||||
assert_eq!(
|
||||
variants[1].url,
|
||||
"https://cdn.example.com/hls/v1/720p60/index.m3u8"
|
||||
);
|
||||
assert_eq!(variants[2].label, "480p");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sanitize_http_headers() {
|
||||
let mut headers = std::collections::HashMap::new();
|
||||
headers.insert("X-Custom".to_string(), "val1,val2".to_string());
|
||||
let (ua, fields) = sanitize_http_headers(Some(&headers)).expect("valid headers");
|
||||
assert!(ua.is_none());
|
||||
assert!(fields.contains("Referer: https://kick.com/"));
|
||||
assert!(fields.contains("Origin: https://kick.com"));
|
||||
assert!(fields.contains("X-Custom: val1 val2"));
|
||||
|
||||
let mut evil = std::collections::HashMap::new();
|
||||
evil.insert("X-Test".to_string(), "bad\r\nInjected: 1".to_string());
|
||||
assert!(sanitize_http_headers(Some(&evil)).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires network and libmpv-2.dll"]
|
||||
async fn test_live_libmpv_kick_stream() {
|
||||
let service = KickApiService::new().expect("KickApiService");
|
||||
let mut chosen_slug = String::new();
|
||||
let mut playback_url = String::new();
|
||||
|
||||
if let Ok(ch) = service.get_channel("wtcn").await {
|
||||
if ch.livestream.is_some() {
|
||||
if let Some(url) = ch.playback_url {
|
||||
chosen_slug = "wtcn".to_string();
|
||||
playback_url = url;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if playback_url.is_empty() {
|
||||
let feed = std::process::Command::new("curl")
|
||||
.args([
|
||||
"-sS",
|
||||
"--max-time",
|
||||
"15",
|
||||
"-H",
|
||||
"Accept: application/json",
|
||||
"https://kick.com/stream/livestreams/en?page=1&limit=3",
|
||||
])
|
||||
.output()
|
||||
.expect("curl feed");
|
||||
let feed_str = String::from_utf8(feed.stdout).expect("utf8 feed");
|
||||
let feed_json: serde_json::Value = serde_json::from_str(&feed_str).expect("feed json");
|
||||
let slug = feed_json["data"][0]["channel"]["slug"]
|
||||
.as_str()
|
||||
.expect("live channel slug")
|
||||
.to_string();
|
||||
let ch = service.get_channel(&slug).await.expect("channel info");
|
||||
chosen_slug = slug;
|
||||
playback_url = ch.playback_url.expect("playback_url");
|
||||
}
|
||||
|
||||
let variants = service
|
||||
.get_hls_variants(&playback_url)
|
||||
.await
|
||||
.expect("get_hls_variants");
|
||||
println!(
|
||||
"[LIVE TEST] Kanal={} | Varyant sayısı={} | İlk={:?}",
|
||||
chosen_slug,
|
||||
variants.len(),
|
||||
variants.first().map(|v| (&v.label, &v.url))
|
||||
);
|
||||
|
||||
let target_url = variants
|
||||
.iter()
|
||||
.find(|v| v.height == 1080)
|
||||
.or_else(|| variants.first())
|
||||
.map(|v| v.url.clone())
|
||||
.unwrap_or(playback_url);
|
||||
|
||||
let report = run_live_smoke_test(&target_url, 12).expect("run_live_smoke_test");
|
||||
println!("[LIVE TEST] MpvSmokeReport: {:#?}", report);
|
||||
|
||||
assert!(report.is_playing, "mpv playback never started");
|
||||
assert!(report.height > 0, "video height remained 0");
|
||||
assert!(!report.video_codec.is_empty(), "video_codec empty");
|
||||
assert!(!report.audio_codec.is_empty(), "audio_codec empty");
|
||||
assert!(report.segments_streamed >= 1, "no piped segments streamed");
|
||||
assert!(report.bytes_streamed > 0, "no piped bytes streamed");
|
||||
assert!(report.error.is_none(), "mpv error: {:?}", report.error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hls_pipe_canonical_key_strips_kick_dna() {
|
||||
let a = "https://fa723fc1b171.cloudfront.hls.live-video.net/v1/segment/ABC123.ts?dna=TokenOne111";
|
||||
let b = "https://fa723fc1b171.cloudfront.hls.live-video.net/v1/segment/ABC123.ts?dna=TokenTwo222";
|
||||
assert_eq!(canonical_segment_key(a, None), canonical_segment_key(b, None));
|
||||
assert_eq!(
|
||||
canonical_segment_key(a, None),
|
||||
"https://fa723fc1b171.cloudfront.hls.live-video.net/v1/segment/ABC123.ts"
|
||||
);
|
||||
|
||||
let c = "https://cdn.example.com/seg.ts?token=keepme&dna=dropme";
|
||||
let d = "https://cdn.example.com/seg.ts?token=keepme&dna=other";
|
||||
assert_eq!(canonical_segment_key(c, None), canonical_segment_key(d, None));
|
||||
assert_eq!(
|
||||
canonical_segment_key(c, Some((100, 500))),
|
||||
"https://cdn.example.com/seg.ts?token=keepme@100+500"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hls_pipe_kick_prefetch_manifest_and_dedup() {
|
||||
let url = "https://fa723fc1b171.euc12.playlist.live-video.net/v1/playlist/var.m3u8";
|
||||
let m3u8 = r#"#EXTM3U
|
||||
#EXT-X-VERSION:3
|
||||
#EXT-X-TARGETDURATION:6
|
||||
#EXT-X-MEDIA-SEQUENCE:26248
|
||||
#EXT-X-DATERANGE:ID="playlist-creation-1795109300",CLASS="timestamp",START-DATE="2026-11-19T17:28:06.000Z",END-ON-NEXT=YES,X-SERVER-TIME="1795109286.00"
|
||||
#EXT-X-PROGRAM-DATE-TIME:2026-11-19T17:27:58.000Z
|
||||
#EXTINF:2.000,live
|
||||
https://cdn.example.net/v1/segment/SEG_OLD.ts?dna=dna1
|
||||
#EXT-X-PROGRAM-DATE-TIME:2026-11-19T17:28:00.000Z
|
||||
#EXTINF:2.000,live
|
||||
https://cdn.example.net/v1/segment/SEG_LAST.ts?dna=dna1
|
||||
#EXT-X-PREFETCH:https://cdn.example.net/v1/segment/PREF_0.ts?dna=dna1
|
||||
#EXT-X-PREFETCH:https://cdn.example.net/v1/segment/PREF_1.ts?dna=dna1
|
||||
"#;
|
||||
let parsed = parse_media_playlist(url, m3u8);
|
||||
assert!(!parsed.is_master);
|
||||
assert!(!parsed.has_encryption);
|
||||
assert!(!parsed.has_init_map);
|
||||
assert_eq!(parsed.segments.len(), 2);
|
||||
assert_eq!(parsed.prefetches.len(), 2);
|
||||
assert_eq!(parsed.prefetches[0].duration_secs, 2.0);
|
||||
assert_eq!(
|
||||
parsed.prefetches[0].canonical_key,
|
||||
"https://cdn.example.net/v1/segment/PREF_0.ts"
|
||||
);
|
||||
|
||||
let mut seen = SeenTracker::new(64);
|
||||
let (mode, initial, _hint) =
|
||||
select_initial_segments(&parsed, &mut seen).expect("prefetch selection");
|
||||
assert_eq!(mode, PipeMode::Prefetch);
|
||||
assert_eq!(initial.len(), 2);
|
||||
assert_eq!(
|
||||
initial[0].canonical_key,
|
||||
"https://cdn.example.net/v1/segment/PREF_0.ts"
|
||||
);
|
||||
assert_eq!(
|
||||
initial[1].canonical_key,
|
||||
"https://cdn.example.net/v1/segment/PREF_1.ts"
|
||||
);
|
||||
|
||||
let next_m3u8 = r#"#EXTM3U
|
||||
#EXT-X-TARGETDURATION:6
|
||||
#EXT-X-MEDIA-SEQUENCE:26249
|
||||
#EXTINF:2.000,live
|
||||
https://cdn.example.net/v1/segment/SEG_LAST.ts?dna=dna2
|
||||
#EXTINF:2.000,live
|
||||
https://cdn.example.net/v1/segment/PREF_0.ts?dna=dna2
|
||||
#EXT-X-PREFETCH:https://cdn.example.net/v1/segment/PREF_1.ts?dna=dna2
|
||||
#EXT-X-PREFETCH:https://cdn.example.net/v1/segment/PREF_2.ts?dna=dna2
|
||||
"#;
|
||||
let next_parsed = parse_media_playlist(url, next_m3u8);
|
||||
let queued = collect_new_segments(mode, &next_parsed, &mut seen);
|
||||
assert_eq!(queued.len(), 1);
|
||||
assert_eq!(
|
||||
queued[0].canonical_key,
|
||||
"https://cdn.example.net/v1/segment/PREF_2.ts"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hls_pipe_llhls_parts_relative_uri_and_byterange() {
|
||||
let url = "https://stream.example.com/live/high/playlist.m3u8";
|
||||
let m3u8 = r#"#EXTM3U
|
||||
#EXT-X-TARGETDURATION:2
|
||||
#EXTINF:2.000,
|
||||
seg100.ts
|
||||
#EXT-X-PART:DURATION=0.33333,URI="part101_0.ts",BYTERANGE="18800@0"
|
||||
#EXT-X-PART:DURATION=0.33333,URI="part101_1.ts",INDEPENDENT=YES,BYTERANGE="22560"
|
||||
#EXT-X-PART:DURATION=0.33333,URI="part101_2.ts",BYTERANGE="19740"
|
||||
"#;
|
||||
let parsed = parse_media_playlist(url, m3u8);
|
||||
assert!(!parsed.has_init_map);
|
||||
assert_eq!(parsed.parts.len(), 3);
|
||||
assert!(!parsed.parts[0].independent);
|
||||
assert!(parsed.parts[1].independent);
|
||||
assert_eq!(
|
||||
parsed.parts[1].url,
|
||||
"https://stream.example.com/live/high/part101_1.ts"
|
||||
);
|
||||
assert_eq!(parsed.parts[0].byte_range, Some((0, 18800)));
|
||||
assert_eq!(parsed.parts[1].byte_range, Some((18800, 22560)));
|
||||
assert_eq!(parsed.parts[2].byte_range, Some((41360, 19740)));
|
||||
|
||||
let mut seen = SeenTracker::new(64);
|
||||
let (mode, initial, _hint) =
|
||||
select_initial_segments(&parsed, &mut seen).expect("llhls selection");
|
||||
assert_eq!(mode, PipeMode::LlHlsPart);
|
||||
assert_eq!(initial.len(), 2);
|
||||
assert_eq!(
|
||||
initial[0].url,
|
||||
"https://stream.example.com/live/high/part101_1.ts"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hls_pipe_detects_encrypted_and_fmp4_for_fallback() {
|
||||
let url = "https://cdn.example.com/live/playlist.m3u8";
|
||||
let encrypted = "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"key.bin\"\n#EXTINF:2.0\nseg1.ts\n";
|
||||
let p_enc = parse_media_playlist(url, encrypted);
|
||||
assert!(p_enc.has_encryption);
|
||||
|
||||
let fmp4 = "#EXTM3U\n#EXT-X-MAP:URI=\"init.mp4\"\n#EXTINF:2.0\nseg1.m4s\n";
|
||||
let p_fmp4 = parse_media_playlist(url, fmp4);
|
||||
assert!(p_fmp4.has_init_map);
|
||||
|
||||
let clear = "#EXTM3U\n#EXT-X-KEY:METHOD=NONE\n#EXTINF:2.0\nseg1.ts\n";
|
||||
let p_clear = parse_media_playlist(url, clear);
|
||||
assert!(!p_clear.has_encryption);
|
||||
assert!(!p_clear.has_init_map);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_followed_page_live_and_offline() {
|
||||
let payload = r#"{
|
||||
"nextCursor": 10,
|
||||
"channels": [
|
||||
{
|
||||
"channel_id": 24783370,
|
||||
"is_live": true,
|
||||
"profile_picture": "https://files.kick.com/images/user/1/pic.webp",
|
||||
"channel_slug": "Hype",
|
||||
"viewer_count": 14327,
|
||||
"category_name": "GTA",
|
||||
"session_title": "Live Stream!"
|
||||
},
|
||||
{
|
||||
"channel_slug": "@OfflineUser",
|
||||
"is_live": false,
|
||||
"viewer_count": 0,
|
||||
"category_name": "",
|
||||
"session_title": ""
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
|
||||
let (entries, next_cursor) = parse_followed_page(payload).expect("valid followed page");
|
||||
assert_eq!(next_cursor, Some(10));
|
||||
assert_eq!(entries.len(), 2);
|
||||
|
||||
assert_eq!(entries[0].channel_slug, "hype");
|
||||
assert!(entries[0].is_live);
|
||||
assert_eq!(entries[0].viewers, 14327);
|
||||
assert_eq!(entries[0].category, "GTA");
|
||||
assert_eq!(entries[0].title, "Live Stream!");
|
||||
assert_eq!(
|
||||
entries[0].avatar_url,
|
||||
"https://files.kick.com/images/user/1/pic.webp"
|
||||
);
|
||||
|
||||
assert_eq!(entries[1].channel_slug, "offlineuser");
|
||||
assert!(!entries[1].is_live);
|
||||
assert_eq!(entries[1].viewers, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_channel_cache_roundtrip() {
|
||||
let cards = vec![
|
||||
ChannelCard {
|
||||
channel_name: "hype".to_string(),
|
||||
is_live: true,
|
||||
title: "Gaming".to_string(),
|
||||
category: "FPS".to_string(),
|
||||
viewers: 5000,
|
||||
verified: true,
|
||||
avatar_url: "https://files.kick.com/a.webp".to_string(),
|
||||
group_name: Some("Favs".to_string()),
|
||||
is_playing: false,
|
||||
chatroom_id: Some(99),
|
||||
playback_url: Some("https://cdn.example/master.m3u8".to_string()),
|
||||
thumbnail_url: Some("https://images.kick.com/thumb.webp".to_string()),
|
||||
started_at: Some("2026-11-20T12:00:00+00:00".to_string()),
|
||||
},
|
||||
ChannelCard::new_offline("someone".to_string(), None),
|
||||
];
|
||||
|
||||
let json = serde_json::to_string(&cards).expect("serialize channel cache");
|
||||
let parsed: Vec<ChannelCard> =
|
||||
serde_json::from_str(&json).expect("deserialize channel cache");
|
||||
assert_eq!(parsed, cards);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_chat_message_includes_source_identity() {
|
||||
let msg = ChatMessage {
|
||||
id: "msg-1".to_string(),
|
||||
username: "tester".to_string(),
|
||||
color_hex: "#60E0B1".to_string(),
|
||||
message: "selam".to_string(),
|
||||
raw_message: "selam".to_string(),
|
||||
timestamp: "22:55".to_string(),
|
||||
badges: Vec::new(),
|
||||
user_id: Some(77),
|
||||
chatroom_id: 123456,
|
||||
channel_slug: "hype".to_string(),
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&msg).expect("serialize chat message");
|
||||
let decoded: ChatMessage = serde_json::from_str(&json).expect("deserialize chat message");
|
||||
assert_eq!(decoded.chatroom_id, 123456);
|
||||
assert_eq!(decoded.channel_slug, "hype");
|
||||
assert_eq!(decoded.id, "msg-1");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_kick_api_channel_cache_hits_without_network() {
|
||||
let api = KickApiService::new().expect("KickApiService");
|
||||
assert!(api.get_cached_channel("hype").is_none());
|
||||
|
||||
let sample = KickChannelResponse {
|
||||
id: Some(42),
|
||||
slug: Some("hype".to_string()),
|
||||
verified: true,
|
||||
playback_url: Some("https://cdn.example/master.m3u8".to_string()),
|
||||
user: None,
|
||||
livestream: None,
|
||||
chatroom: None,
|
||||
};
|
||||
api.store_cached_channel("hype", &sample);
|
||||
|
||||
let cached = api
|
||||
.get_channel(" @Hype ")
|
||||
.await
|
||||
.expect("get_channel should serve fresh in-memory cache without network");
|
||||
assert_eq!(cached.id, Some(42));
|
||||
assert_eq!(cached.slug.as_deref(), Some("hype"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_top_tr_livestreams_filters_turkish_and_extracts_fields() {
|
||||
let payload = r#"{
|
||||
"data": [
|
||||
{
|
||||
"session_title": "GTA RP Gecesi",
|
||||
"is_live": true,
|
||||
"language": "Turkish",
|
||||
"viewer_count": 48500,
|
||||
"thumbnail": { "src": "https://images.kick.com/tr1.webp" },
|
||||
"categories": [{ "name": "Grand Theft Auto V" }],
|
||||
"channel": {
|
||||
"slug": "Rraenee",
|
||||
"playback_url": "https://cdn.example/rraenee.m3u8",
|
||||
"user": { "profilepic": "https://files.kick.com/rraenee.webp" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"session_title": "English Only",
|
||||
"is_live": true,
|
||||
"language": "English",
|
||||
"viewer_count": 90000,
|
||||
"channel": {
|
||||
"slug": "englishstreamer",
|
||||
"user": { "profilepic": "" }
|
||||
}
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
|
||||
let parsed = parse_top_tr_livestreams(payload, true);
|
||||
assert_eq!(parsed.len(), 1);
|
||||
assert_eq!(parsed[0].channel_name, "rraenee");
|
||||
assert_eq!(parsed[0].viewers, 48500);
|
||||
assert_eq!(parsed[0].category, "Grand Theft Auto V");
|
||||
assert_eq!(parsed[0].title, "GTA RP Gecesi");
|
||||
assert_eq!(
|
||||
parsed[0].thumbnail_url.as_deref(),
|
||||
Some("https://images.kick.com/tr1.webp")
|
||||
);
|
||||
assert_eq!(
|
||||
parsed[0].playback_url.as_deref(),
|
||||
Some("https://cdn.example/rraenee.m3u8")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_small_tr_livestreams_keeps_5_to_30_unique_random_15() {
|
||||
let mk = |name: &str, viewers: i64, live: bool| ChannelCard {
|
||||
channel_name: name.to_string(),
|
||||
is_live: live,
|
||||
title: String::new(),
|
||||
category: String::new(),
|
||||
viewers,
|
||||
verified: false,
|
||||
avatar_url: String::new(),
|
||||
group_name: None,
|
||||
is_playing: false,
|
||||
chatroom_id: None,
|
||||
playback_url: None,
|
||||
thumbnail_url: None,
|
||||
started_at: None,
|
||||
};
|
||||
|
||||
let mut input = vec![
|
||||
mk("too_low", 4, true),
|
||||
mk("too_high", 31, true),
|
||||
mk("offline_chan", 12, false),
|
||||
mk("dup_chan", 17, true),
|
||||
mk("dup_chan", 17, true),
|
||||
];
|
||||
for i in 0..20 {
|
||||
input.push(mk(&format!("small_{}", i), 5 + (i % 26), true));
|
||||
}
|
||||
|
||||
let picked = filter_small_tr_livestreams(input.clone(), 5, 30, 15, 12345);
|
||||
assert_eq!(picked.len(), 15);
|
||||
assert!(picked.iter().all(|c| c.is_live && (5..=30).contains(&c.viewers)));
|
||||
|
||||
let picked_other = filter_small_tr_livestreams(input, 5, 30, 15, 987654321);
|
||||
assert_eq!(picked_other.len(), 15);
|
||||
let names_a: Vec<&str> = picked.iter().map(|c| c.channel_name.as_str()).collect();
|
||||
let names_b: Vec<&str> = picked_other.iter().map(|c| c.channel_name.as_str()).collect();
|
||||
assert_ne!(names_a, names_b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_normalize_kick_utc_timestamp() {
|
||||
assert_eq!(
|
||||
normalize_kick_utc_timestamp("2026-11-20 12:06:26").as_deref(),
|
||||
Some("2026-11-20T12:06:26+00:00")
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_kick_utc_timestamp("2026-11-20T12:06:26.123Z").as_deref(),
|
||||
Some("2026-11-20T12:06:26.123+00:00")
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_kick_utc_timestamp("2026-11-20T15:06:26+03:00").as_deref(),
|
||||
Some("2026-11-20T12:06:26+00:00")
|
||||
);
|
||||
assert!(normalize_kick_utc_timestamp("").is_none());
|
||||
assert!(normalize_kick_utc_timestamp("not-a-timestamp").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_media_playlist_extracts_stream_total_secs() {
|
||||
let playlist = "\
|
||||
#EXTM3U
|
||||
#EXT-X-VERSION:3
|
||||
#EXT-X-TARGETDURATION:6
|
||||
#EXT-X-NET-LIVE-VIDEO-TOTAL-SECS:9564.000
|
||||
#EXTINF:2.000,live
|
||||
seg1.ts
|
||||
";
|
||||
let parsed = parse_media_playlist("https://cdn.example/playlist.m3u8", playlist);
|
||||
assert_eq!(parsed.stream_total_secs, Some(9564.0));
|
||||
|
||||
let twitch_style = "\
|
||||
#EXTM3U
|
||||
#EXT-X-TARGETDURATION:10
|
||||
#EXT-X-TWITCH-TOTAL-SECS:9606.500
|
||||
#EXTINF:10.000,
|
||||
0.ts
|
||||
";
|
||||
let parsed2 = parse_media_playlist("https://stream.kick.com/vod/playlist.m3u8", twitch_style);
|
||||
assert_eq!(parsed2.stream_total_secs, Some(9606.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_live_dvr_video_source_picks_active_live_vod() {
|
||||
let payload = r#"[
|
||||
{
|
||||
"id": 100,
|
||||
"is_live": false,
|
||||
"start_time": "2026-11-19 10:00:00",
|
||||
"source": "https://stream.kick.com/old_vod/master.m3u8"
|
||||
},
|
||||
{
|
||||
"id": 101,
|
||||
"is_live": true,
|
||||
"start_time": "2026-11-20 12:06:26",
|
||||
"source": "https://stream.kick.com/live_dvr/master.m3u8"
|
||||
}
|
||||
]"#;
|
||||
let parsed = parse_live_dvr_video_source(payload);
|
||||
assert_eq!(
|
||||
parsed,
|
||||
Some((
|
||||
"https://stream.kick.com/live_dvr/master.m3u8".to_string(),
|
||||
Some("2026-11-20T12:06:26+00:00".to_string())
|
||||
))
|
||||
);
|
||||
|
||||
let offline_only = r#"[{"id":1,"is_live":false,"source":"https://stream.kick.com/x.m3u8"}]"#;
|
||||
assert!(parse_live_dvr_video_source(offline_only).is_none());
|
||||
|
||||
let local_ssrf = r#"[{"id":2,"is_live":true,"source":"http://127.0.0.1/evil.m3u8"}]"#;
|
||||
assert!(parse_live_dvr_video_source(local_ssrf).is_none());
|
||||
}
|
||||
}
|
||||
40
src-tauri/src/models/channel.rs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct ChannelCard {
|
||||
pub channel_name: String,
|
||||
pub is_live: bool,
|
||||
pub title: String,
|
||||
pub category: String,
|
||||
pub viewers: i64,
|
||||
pub verified: bool,
|
||||
pub avatar_url: String,
|
||||
pub group_name: Option<String>,
|
||||
pub is_playing: bool,
|
||||
pub chatroom_id: Option<i64>,
|
||||
pub playback_url: Option<String>,
|
||||
#[serde(default)]
|
||||
pub thumbnail_url: Option<String>,
|
||||
#[serde(default)]
|
||||
pub started_at: Option<String>,
|
||||
}
|
||||
|
||||
impl ChannelCard {
|
||||
pub fn new_offline(name: String, group_name: Option<String>) -> Self {
|
||||
Self {
|
||||
channel_name: name,
|
||||
is_live: false,
|
||||
title: String::new(),
|
||||
category: String::new(),
|
||||
viewers: 0,
|
||||
verified: false,
|
||||
avatar_url: String::new(),
|
||||
group_name,
|
||||
is_playing: false,
|
||||
chatroom_id: None,
|
||||
playback_url: None,
|
||||
thumbnail_url: None,
|
||||
started_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
31
src-tauri/src/models/chat.rs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ChatBadge {
|
||||
#[serde(rename = "type")]
|
||||
pub badge_type: String,
|
||||
#[serde(default)]
|
||||
pub text: String,
|
||||
#[serde(default)]
|
||||
pub count: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ChatMessage {
|
||||
pub id: String,
|
||||
pub username: String,
|
||||
pub color_hex: String,
|
||||
pub message: String,
|
||||
pub raw_message: String,
|
||||
pub timestamp: String,
|
||||
#[serde(default)]
|
||||
pub badges: Vec<ChatBadge>,
|
||||
#[serde(default)]
|
||||
pub user_id: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub chatroom_id: i64,
|
||||
#[serde(default)]
|
||||
pub channel_slug: String,
|
||||
}
|
||||
255
src-tauri/src/models/config.rs
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AppConfig {
|
||||
#[serde(default = "default_favorites")]
|
||||
pub favorites: Vec<String>,
|
||||
|
||||
#[serde(default)]
|
||||
pub channel_groups: HashMap<String, String>,
|
||||
|
||||
#[serde(default = "default_player_choice")]
|
||||
pub player_choice: String,
|
||||
|
||||
#[serde(default = "default_player_choice")]
|
||||
pub player_type: String,
|
||||
|
||||
#[serde(default = "default_refresh_interval")]
|
||||
pub refresh_interval_seconds: u64,
|
||||
|
||||
#[serde(default)]
|
||||
pub start_minimized: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub minimize_to_tray: bool,
|
||||
|
||||
#[serde(default = "default_true")]
|
||||
pub notifications_enabled: bool,
|
||||
|
||||
#[serde(default = "default_true")]
|
||||
pub sound_notifications_enabled: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub custom_sound_path: String,
|
||||
|
||||
#[serde(default = "default_true")]
|
||||
pub notify_on_category_change: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub alert_keywords: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub run_on_startup: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub auto_open_chat: bool,
|
||||
|
||||
#[serde(default = "default_true")]
|
||||
pub show_embedded_chat: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub streamlink_path: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub player_path: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub vlc_path: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub mpv_path: String,
|
||||
|
||||
#[serde(default = "default_quality")]
|
||||
pub stream_quality: String,
|
||||
|
||||
#[serde(default = "default_quality")]
|
||||
pub default_quality: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub extra_streamlink_args: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub custom_player_args: String,
|
||||
|
||||
#[serde(default = "default_chat_max_messages")]
|
||||
pub chat_max_messages: usize,
|
||||
|
||||
#[serde(default)]
|
||||
pub squad_view_slots: Vec<String>,
|
||||
|
||||
#[serde(default = "default_true")]
|
||||
pub dark_mode: bool,
|
||||
|
||||
#[serde(default = "default_true")]
|
||||
pub auto_update_on_startup: bool,
|
||||
|
||||
#[serde(default = "default_volume")]
|
||||
pub volume: u8,
|
||||
|
||||
#[serde(default)]
|
||||
pub muted: bool,
|
||||
|
||||
#[serde(default = "default_window_width")]
|
||||
pub window_width: u32,
|
||||
|
||||
#[serde(default = "default_window_height")]
|
||||
pub window_height: u32,
|
||||
|
||||
#[serde(default)]
|
||||
pub window_x: Option<i32>,
|
||||
|
||||
#[serde(default)]
|
||||
pub window_y: Option<i32>,
|
||||
|
||||
#[serde(default)]
|
||||
pub window_maximized: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub kick_token: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub kick_user_id: Option<i64>,
|
||||
|
||||
#[serde(default)]
|
||||
pub kick_username: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub kick_avatar: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub kick_cookies: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub kick_xsrf: String,
|
||||
|
||||
#[serde(default)]
|
||||
pub kick_user_agent: String,
|
||||
|
||||
#[serde(default = "default_kick_color")]
|
||||
pub kick_chat_color: String,
|
||||
}
|
||||
|
||||
fn default_favorites() -> Vec<String> {
|
||||
vec![
|
||||
"elwind".to_string(),
|
||||
"wtcn".to_string(),
|
||||
"pqueen".to_string(),
|
||||
"unlostv".to_string(),
|
||||
"kendinemuzisyen".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
fn default_player_choice() -> String {
|
||||
"internal".to_string()
|
||||
}
|
||||
|
||||
fn default_refresh_interval() -> u64 {
|
||||
60
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_quality() -> String {
|
||||
"best".to_string()
|
||||
}
|
||||
|
||||
fn default_chat_max_messages() -> usize {
|
||||
500
|
||||
}
|
||||
|
||||
fn default_volume() -> u8 {
|
||||
100
|
||||
}
|
||||
|
||||
fn default_window_width() -> u32 {
|
||||
1340
|
||||
}
|
||||
|
||||
fn default_window_height() -> u32 {
|
||||
820
|
||||
}
|
||||
|
||||
fn default_kick_color() -> String {
|
||||
"#60E0B1".to_string()
|
||||
}
|
||||
|
||||
impl Default for AppConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
favorites: default_favorites(),
|
||||
channel_groups: HashMap::new(),
|
||||
player_choice: default_player_choice(),
|
||||
player_type: default_player_choice(),
|
||||
refresh_interval_seconds: default_refresh_interval(),
|
||||
start_minimized: false,
|
||||
minimize_to_tray: false,
|
||||
notifications_enabled: true,
|
||||
sound_notifications_enabled: true,
|
||||
custom_sound_path: String::new(),
|
||||
notify_on_category_change: true,
|
||||
alert_keywords: String::new(),
|
||||
run_on_startup: false,
|
||||
auto_open_chat: false,
|
||||
show_embedded_chat: true,
|
||||
streamlink_path: String::new(),
|
||||
player_path: String::new(),
|
||||
vlc_path: String::new(),
|
||||
mpv_path: String::new(),
|
||||
stream_quality: default_quality(),
|
||||
default_quality: default_quality(),
|
||||
extra_streamlink_args: String::new(),
|
||||
custom_player_args: String::new(),
|
||||
chat_max_messages: default_chat_max_messages(),
|
||||
squad_view_slots: vec![String::new(), String::new(), String::new(), String::new()],
|
||||
dark_mode: true,
|
||||
auto_update_on_startup: true,
|
||||
volume: 100,
|
||||
muted: false,
|
||||
window_width: default_window_width(),
|
||||
window_height: default_window_height(),
|
||||
window_x: None,
|
||||
window_y: None,
|
||||
window_maximized: false,
|
||||
kick_token: String::new(),
|
||||
kick_user_id: None,
|
||||
kick_username: String::new(),
|
||||
kick_avatar: String::new(),
|
||||
kick_cookies: String::new(),
|
||||
kick_xsrf: String::new(),
|
||||
kick_user_agent: String::new(),
|
||||
kick_chat_color: default_kick_color(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_app_config_default_values() {
|
||||
let cfg = AppConfig::default();
|
||||
assert!(!cfg.favorites.is_empty());
|
||||
assert!(cfg.favorites.contains(&"wtcn".to_string()));
|
||||
assert!(cfg.notifications_enabled);
|
||||
assert!(cfg.auto_update_on_startup);
|
||||
assert_eq!(cfg.refresh_interval_seconds, 60);
|
||||
assert_eq!(cfg.squad_view_slots.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_app_config_serde_roundtrip() {
|
||||
let mut cfg = AppConfig::default();
|
||||
cfg.favorites.push("test_streamer".to_string());
|
||||
cfg.player_type = "mpv".to_string();
|
||||
|
||||
let json = serde_json::to_string(&cfg).expect("Serialization failed");
|
||||
let decoded: AppConfig = serde_json::from_str(&json).expect("Deserialization failed");
|
||||
|
||||
assert_eq!(decoded.favorites, cfg.favorites);
|
||||
assert_eq!(decoded.player_type, "mpv");
|
||||
}
|
||||
}
|
||||
51
src-tauri/src/models/kick_api.rs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KickCategory {
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KickLivestream {
|
||||
pub session_title: Option<String>,
|
||||
pub viewer_count: Option<i64>,
|
||||
pub categories: Option<Vec<KickCategory>>,
|
||||
pub start_time: Option<String>,
|
||||
pub created_at: Option<String>,
|
||||
}
|
||||
|
||||
impl KickLivestream {
|
||||
pub fn normalized_started_at(&self) -> Option<String> {
|
||||
self.start_time
|
||||
.as_deref()
|
||||
.and_then(crate::services::kick_api::normalize_kick_utc_timestamp)
|
||||
.or_else(|| {
|
||||
self.created_at
|
||||
.as_deref()
|
||||
.and_then(crate::services::kick_api::normalize_kick_utc_timestamp)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KickUser {
|
||||
pub username: Option<String>,
|
||||
pub profile_pic: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KickChatroom {
|
||||
pub id: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KickChannelResponse {
|
||||
pub id: Option<i64>,
|
||||
pub slug: Option<String>,
|
||||
#[serde(default)]
|
||||
pub verified: bool,
|
||||
pub playback_url: Option<String>,
|
||||
pub user: Option<KickUser>,
|
||||
pub livestream: Option<KickLivestream>,
|
||||
pub chatroom: Option<KickChatroom>,
|
||||
}
|
||||
9
src-tauri/src/models/mod.rs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
pub mod channel;
|
||||
pub mod chat;
|
||||
pub mod config;
|
||||
pub mod kick_api;
|
||||
|
||||
pub use channel::ChannelCard;
|
||||
pub use chat::{ChatBadge, ChatMessage};
|
||||
pub use config::AppConfig;
|
||||
pub use kick_api::*;
|
||||
276
src-tauri/src/services/chat.rs
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
use crate::error::AppError;
|
||||
use crate::models::ChatMessage;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::{json, Value};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tauri::async_runtime::JoinHandle;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
struct ActiveChatSession {
|
||||
session_id: u64,
|
||||
chatroom_id: i64,
|
||||
join_handle: JoinHandle<()>,
|
||||
ctrl_tx: mpsc::UnboundedSender<String>,
|
||||
}
|
||||
|
||||
pub struct PusherChatService {
|
||||
pub app_handle: AppHandle,
|
||||
session_counter: Arc<AtomicU64>,
|
||||
current_channel: Arc<Mutex<Option<(String, i64)>>>,
|
||||
active_session: Arc<Mutex<Option<ActiveChatSession>>>,
|
||||
}
|
||||
|
||||
impl PusherChatService {
|
||||
pub fn new(app_handle: AppHandle) -> Self {
|
||||
Self {
|
||||
app_handle,
|
||||
session_counter: Arc::new(AtomicU64::new(0)),
|
||||
current_channel: Arc::new(Mutex::new(None)),
|
||||
active_session: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn connect(&self, channel_name: &str, chatroom_id: i64) -> Result<(), AppError> {
|
||||
self.disconnect().await;
|
||||
|
||||
let channel_name = channel_name.trim().trim_start_matches('@').to_lowercase();
|
||||
let session_id = self.session_counter.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
|
||||
{
|
||||
let mut cur = self.current_channel.lock().await;
|
||||
*cur = Some((channel_name.clone(), chatroom_id));
|
||||
}
|
||||
|
||||
let session_counter = Arc::clone(&self.session_counter);
|
||||
let app_handle = self.app_handle.clone();
|
||||
let (ctrl_tx, mut ctrl_rx) = mpsc::unbounded_channel::<String>();
|
||||
let slug_owned = channel_name.clone();
|
||||
|
||||
let join_handle = tauri::async_runtime::spawn(async move {
|
||||
let mut reconnect_attempt: u32 = 0;
|
||||
|
||||
while session_counter.load(Ordering::SeqCst) == session_id {
|
||||
let ws_url = "wss://ws-us2.pusher.com/app/34bf7a0ff419a2a775b9?protocol=7&client=js&version=8.4.0&flash=false";
|
||||
|
||||
match connect_async(ws_url).await {
|
||||
Ok((ws_stream, _)) => {
|
||||
if session_counter.load(Ordering::SeqCst) != session_id {
|
||||
break;
|
||||
}
|
||||
|
||||
reconnect_attempt = 0;
|
||||
let _ = app_handle.emit("chat-connection-state", true);
|
||||
|
||||
let (mut write, mut read) = ws_stream.split();
|
||||
let mut ping_interval = tokio::time::interval(Duration::from_secs(30));
|
||||
ping_interval.tick().await;
|
||||
|
||||
while session_counter.load(Ordering::SeqCst) == session_id {
|
||||
tokio::select! {
|
||||
Some(unsub_payload) = ctrl_rx.recv() => {
|
||||
let _ = write.send(Message::Text(unsub_payload.into())).await;
|
||||
let _ = write.send(Message::Close(None)).await;
|
||||
return;
|
||||
}
|
||||
_ = ping_interval.tick() => {
|
||||
let ping_msg = json!({
|
||||
"event": "pusher:ping",
|
||||
"data": {}
|
||||
});
|
||||
if let Err(e) = write.send(Message::Text(ping_msg.to_string().into())).await {
|
||||
log::warn!("Pusher ping iletim hatası: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
msg = read.next() => {
|
||||
if session_counter.load(Ordering::SeqCst) != session_id {
|
||||
let unsub = json!({
|
||||
"event": "pusher:unsubscribe",
|
||||
"data": { "channel": format!("chatrooms.{}.v2", chatroom_id) }
|
||||
});
|
||||
let _ = write.send(Message::Text(unsub.to_string().into())).await;
|
||||
let _ = write.send(Message::Close(None)).await;
|
||||
return;
|
||||
}
|
||||
|
||||
match msg {
|
||||
Some(Ok(Message::Text(text))) => {
|
||||
if let Ok(v) = serde_json::from_str::<Value>(&text) {
|
||||
let event = v.get("event").and_then(|e| e.as_str()).unwrap_or("");
|
||||
|
||||
if event == "pusher:connection_established" {
|
||||
let sub_payload = json!({
|
||||
"event": "pusher:subscribe",
|
||||
"data": {
|
||||
"auth": "",
|
||||
"channel": format!("chatrooms.{}.v2", chatroom_id)
|
||||
}
|
||||
});
|
||||
let _ = write.send(Message::Text(sub_payload.to_string().into())).await;
|
||||
} else if event == "pusher:ping" {
|
||||
let pong = json!({
|
||||
"event": "pusher:pong",
|
||||
"data": {}
|
||||
});
|
||||
let _ = write.send(Message::Text(pong.to_string().into())).await;
|
||||
} else if event == "App\\Events\\ChatMessageEvent" || event == "ChatMessageEvent" {
|
||||
if session_counter.load(Ordering::SeqCst) != session_id {
|
||||
return;
|
||||
}
|
||||
if let Some(data_str) = v.get("data").and_then(|d| d.as_str()) {
|
||||
if let Ok(inner) = serde_json::from_str::<Value>(data_str) {
|
||||
let raw_content = inner.get("content").and_then(|c| c.as_str()).unwrap_or("").to_string();
|
||||
let content = raw_content.clone();
|
||||
|
||||
let sender = inner.get("sender");
|
||||
let username = sender
|
||||
.and_then(|s| s.get("username"))
|
||||
.and_then(|u| u.as_str())
|
||||
.unwrap_or("?")
|
||||
.to_string();
|
||||
|
||||
let color_hex = sender
|
||||
.and_then(|s| s.get("identity"))
|
||||
.and_then(|i| i.get("color"))
|
||||
.and_then(|c| c.as_str())
|
||||
.unwrap_or("#60E0B1")
|
||||
.to_string();
|
||||
|
||||
let user_id = sender
|
||||
.and_then(|s| s.get("id"))
|
||||
.and_then(|i| i.as_i64());
|
||||
|
||||
let badges = badges_from_sender(sender);
|
||||
let msg_id = inner
|
||||
.get("id")
|
||||
.and_then(|i| i.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| chrono::Local::now().timestamp_millis().to_string());
|
||||
|
||||
let time_str = chrono::Local::now().format("%H:%M").to_string();
|
||||
|
||||
let chat_msg = ChatMessage {
|
||||
id: msg_id,
|
||||
username,
|
||||
color_hex,
|
||||
message: content,
|
||||
raw_message: raw_content,
|
||||
timestamp: time_str,
|
||||
badges,
|
||||
user_id,
|
||||
chatroom_id,
|
||||
channel_slug: slug_owned.clone(),
|
||||
};
|
||||
|
||||
if session_counter.load(Ordering::SeqCst) == session_id {
|
||||
let _ = app_handle.emit("chat-message", &chat_msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Ok(Message::Close(_))) | None => {
|
||||
break;
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
log::warn!("Pusher okuma hatası: {}", e);
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Pusher bağlantı hatası: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
if session_counter.load(Ordering::SeqCst) != session_id {
|
||||
break;
|
||||
}
|
||||
|
||||
let _ = app_handle.emit("chat-connection-state", false);
|
||||
|
||||
reconnect_attempt = reconnect_attempt.saturating_add(1);
|
||||
let delay_secs = (2u64.pow(reconnect_attempt.min(5))).min(30);
|
||||
tokio::time::sleep(Duration::from_secs(delay_secs)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let mut slot = self.active_session.lock().await;
|
||||
*slot = Some(ActiveChatSession {
|
||||
session_id,
|
||||
chatroom_id,
|
||||
join_handle,
|
||||
ctrl_tx,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn disconnect(&self) {
|
||||
self.session_counter.fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
if let Some(prev) = self.active_session.lock().await.take() {
|
||||
let unsub = json!({
|
||||
"event": "pusher:unsubscribe",
|
||||
"data": { "channel": format!("chatrooms.{}.v2", prev.chatroom_id) }
|
||||
});
|
||||
let _ = prev.ctrl_tx.send(unsub.to_string());
|
||||
let _ = prev.session_id;
|
||||
prev.join_handle.abort();
|
||||
}
|
||||
|
||||
let mut cur = self.current_channel.lock().await;
|
||||
*cur = None;
|
||||
let _ = self.app_handle.emit("chat-connection-state", false);
|
||||
}
|
||||
|
||||
pub async fn get_current_channel(&self) -> Option<(String, i64)> {
|
||||
let cur = self.current_channel.lock().await;
|
||||
cur.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts chat badges from a Pusher `sender` object. Kick has shipped both
|
||||
/// `sender.identity.badges` and `sender.badges` over time, so both are checked.
|
||||
pub fn badges_from_sender(sender: Option<&Value>) -> Vec<crate::models::ChatBadge> {
|
||||
let Some(sender) = sender else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let badges = sender
|
||||
.get("identity")
|
||||
.and_then(|identity| identity.get("badges"))
|
||||
.and_then(|badges| badges.as_array())
|
||||
.or_else(|| sender.get("badges").and_then(|badges| badges.as_array()));
|
||||
|
||||
badges
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|badge| {
|
||||
let badge_type = badge.get("type").and_then(|t| t.as_str())?.to_string();
|
||||
Some(crate::models::ChatBadge {
|
||||
badge_type,
|
||||
text: badge
|
||||
.get("text")
|
||||
.and_then(|t| t.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
count: badge.get("count").and_then(|c| c.as_i64()),
|
||||
active: badge.get("active").and_then(|a| a.as_bool()).unwrap_or(true),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
176
src-tauri/src/services/config.rs
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
use crate::error::AppError;
|
||||
use crate::models::{AppConfig, ChannelCard};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct ConfigService {
|
||||
pub config_path: PathBuf,
|
||||
pub cache_path: PathBuf,
|
||||
pub followed_cache_path: PathBuf,
|
||||
}
|
||||
|
||||
impl ConfigService {
|
||||
pub fn new() -> Result<Self, AppError> {
|
||||
let mut app_dir = dirs::data_local_dir().unwrap_or_else(|| PathBuf::from("."));
|
||||
app_dir.push("LDKickWatch");
|
||||
if let Err(e) = fs::create_dir_all(&app_dir) {
|
||||
log::warn!("LDKickWatch konfigürasyon klasörü oluşturulamadı: {}", e);
|
||||
}
|
||||
|
||||
let config_path = app_dir.join("config.json");
|
||||
let cache_path = app_dir.join("cache.json");
|
||||
let followed_cache_path = app_dir.join("followed_cache.json");
|
||||
|
||||
// Migrate legacy KickStreamHub config if present
|
||||
if !config_path.exists() {
|
||||
let mut legacy = dirs::data_local_dir().unwrap_or_else(|| PathBuf::from("."));
|
||||
legacy.push("KickStreamHub");
|
||||
legacy.push("config.json");
|
||||
if legacy.exists() {
|
||||
if let Err(e) = fs::copy(&legacy, &config_path) {
|
||||
log::warn!("Eski yapılandırma kopyalanamadı: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
config_path,
|
||||
cache_path,
|
||||
followed_cache_path,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn load(&self) -> AppConfig {
|
||||
if !self.config_path.exists() {
|
||||
let default_cfg = AppConfig::default();
|
||||
let _ = self.save(&default_cfg);
|
||||
return default_cfg;
|
||||
}
|
||||
|
||||
match fs::read_to_string(&self.config_path) {
|
||||
Ok(content) => {
|
||||
match serde_json::from_str::<AppConfig>(&content) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(err) => {
|
||||
log::error!(
|
||||
"Yapılandırma dosyası bozuk veya geçersiz JSON! Otomatik kurtarma başlatılıyor: {}",
|
||||
err
|
||||
);
|
||||
|
||||
// Self-healing: Backup corrupted config
|
||||
let timestamp = chrono::Local::now().format("%Y%m%d_%H%M%S");
|
||||
let backup_path = self
|
||||
.config_path
|
||||
.with_extension(format!("corrupted.{}.json", timestamp));
|
||||
let _ = fs::rename(&self.config_path, &backup_path);
|
||||
log::info!(
|
||||
"Bozuk yapılandırma '{}' yoluna yedeklendi.",
|
||||
backup_path.display()
|
||||
);
|
||||
|
||||
// Re-initialize with healthy default configuration
|
||||
let default_cfg = AppConfig::default();
|
||||
if let Err(e) = self.save(&default_cfg) {
|
||||
log::error!("Varsayılan yapılandırma kaydedilemedi: {}", e);
|
||||
}
|
||||
default_cfg
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"Yapılandırma dosyası okunamadı: {}. Varsayılan kullanılıyor.",
|
||||
e
|
||||
);
|
||||
AppConfig::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self, config: &AppConfig) -> Result<(), AppError> {
|
||||
let content = serde_json::to_string_pretty(config)?;
|
||||
|
||||
if let Some(parent) = self.config_path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
}
|
||||
|
||||
let tmp_path = self.config_path.with_extension("tmp");
|
||||
fs::write(&tmp_path, content)?;
|
||||
|
||||
// Attempt rename with retry in case of transient file lock (antivirus/indexing)
|
||||
let mut rename_res = fs::rename(&tmp_path, &self.config_path);
|
||||
if rename_res.is_err() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
rename_res = fs::rename(&tmp_path, &self.config_path);
|
||||
}
|
||||
|
||||
if let Err(e) = rename_res {
|
||||
log::error!("Yapılandırma dosyası atomik olarak yazılamadı: {}", e);
|
||||
let _ = fs::remove_file(&tmp_path);
|
||||
return Err(AppError::Io(e));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_cards_file(path: &PathBuf) -> Vec<ChannelCard> {
|
||||
if !path.exists() {
|
||||
return Vec::new();
|
||||
}
|
||||
match fs::read_to_string(path) {
|
||||
Ok(content) => serde_json::from_str::<Vec<ChannelCard>>(&content).unwrap_or_default(),
|
||||
Err(err) => {
|
||||
log::warn!("Kanal önbelleği okunamadı: {}", err);
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_cards_file(path: &PathBuf, tmp_ext: &str, cards: &[ChannelCard]) {
|
||||
let Ok(content) = serde_json::to_string(cards) else {
|
||||
return;
|
||||
};
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
}
|
||||
let tmp_path = path.with_extension(tmp_ext);
|
||||
if fs::write(&tmp_path, content).is_err() {
|
||||
return;
|
||||
}
|
||||
let mut rename_res = fs::rename(&tmp_path, path);
|
||||
if rename_res.is_err() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(30));
|
||||
rename_res = fs::rename(&tmp_path, path);
|
||||
}
|
||||
if let Err(err) = rename_res {
|
||||
log::debug!("Kanal önbelleği yazılamadı: {}", err);
|
||||
let _ = fs::remove_file(&tmp_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads previously cached guest channel cards (`cache.json`) for instant 0 ms UI startup.
|
||||
pub fn load_channel_cache(&self) -> Vec<ChannelCard> {
|
||||
Self::read_cards_file(&self.cache_path)
|
||||
}
|
||||
|
||||
/// Persists guest channel cards atomically to `cache.json` (best-effort, non-fatal).
|
||||
pub fn save_channel_cache(&self, cards: &[ChannelCard]) {
|
||||
Self::write_cards_file(&self.cache_path, "cache.tmp", cards);
|
||||
}
|
||||
|
||||
/// Loads previously cached Kick followed channel cards (`followed_cache.json`).
|
||||
pub fn load_followed_cache(&self) -> Vec<ChannelCard> {
|
||||
Self::read_cards_file(&self.followed_cache_path)
|
||||
}
|
||||
|
||||
/// Persists authoritative Kick followed channel cards to `followed_cache.json`.
|
||||
pub fn save_followed_cache(&self, cards: &[ChannelCard]) {
|
||||
Self::write_cards_file(&self.followed_cache_path, "followed.tmp", cards);
|
||||
}
|
||||
|
||||
/// Removes both channel cache files cleanly (e.g., on logout).
|
||||
pub fn clear_channel_caches(&self) {
|
||||
let _ = fs::remove_file(&self.followed_cache_path);
|
||||
let _ = fs::remove_file(&self.cache_path);
|
||||
}
|
||||
}
|
||||
1540
src-tauri/src/services/hls_pipe.rs
Normal file
1416
src-tauri/src/services/kick_api.rs
Normal file
183
src-tauri/src/services/kick_auth.rs
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
use crate::error::AppError;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Kick account snapshot shown across the UI. The bearer token itself never
|
||||
/// leaves the backend.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct KickProfile {
|
||||
pub id: i64,
|
||||
pub username: String,
|
||||
pub avatar_url: String,
|
||||
}
|
||||
|
||||
/// Everything the authenticated request engine needs to look like the real
|
||||
/// browser session (Cloudflare `cf_clearance`, session token, CSRF token).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct KickAuthContext {
|
||||
pub token: String,
|
||||
pub cookie_header: String,
|
||||
pub xsrf_token: String,
|
||||
pub user_agent: String,
|
||||
}
|
||||
|
||||
impl KickAuthContext {
|
||||
pub fn is_authenticated(&self) -> bool {
|
||||
!self.token.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Percent-decodes a cookie value (Kick stores the bearer token URL-encoded,
|
||||
/// so `%7C` must become `|` before it can be used as `Authorization: Bearer …`).
|
||||
pub fn percent_decode(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
|
||||
while index < bytes.len() {
|
||||
let byte = bytes[index];
|
||||
if byte == b'%' && index + 2 < bytes.len() {
|
||||
let high = (bytes[index + 1] as char).to_digit(16);
|
||||
let low = (bytes[index + 2] as char).to_digit(16);
|
||||
if let (Some(high), Some(low)) = (high, low) {
|
||||
out.push((high * 16 + low) as u8);
|
||||
index += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(byte);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
String::from_utf8_lossy(&out).to_string()
|
||||
}
|
||||
|
||||
/// Extracts and normalises the bearer token from a raw cookie value or a pasted
|
||||
/// token. Accepts `Bearer ` prefixes, URL-encoded pipes and surrounding quotes.
|
||||
pub fn normalize_session_token(raw: &str) -> String {
|
||||
let trimmed = raw.trim().trim_matches('"').trim();
|
||||
let without_prefix = trimmed
|
||||
.strip_prefix("Bearer ")
|
||||
.or_else(|| trimmed.strip_prefix("bearer "))
|
||||
.unwrap_or(trimmed);
|
||||
percent_decode(without_prefix).trim().to_string()
|
||||
}
|
||||
|
||||
pub fn find_cookie<'a>(cookies: &'a [(String, String)], name: &str) -> Option<&'a str> {
|
||||
cookies
|
||||
.iter()
|
||||
.find(|(key, _)| key.eq_ignore_ascii_case(name))
|
||||
.map(|(_, value)| value.as_str())
|
||||
}
|
||||
|
||||
/// Builds the `Cookie:` header from the cookie jar snapshot.
|
||||
pub fn cookie_header(cookies: &[(String, String)]) -> String {
|
||||
cookies
|
||||
.iter()
|
||||
.filter(|(name, value)| !name.is_empty() && !value.is_empty())
|
||||
.map(|(name, value)| format!("{}={}", name, value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
}
|
||||
|
||||
/// Converts `:emoteName:` shortcuts into Kick's wire format
|
||||
/// `[emote:ID:NAME]` using the channel emote map.
|
||||
pub fn format_emotes(input: &str, emotes: &[(String, String)]) -> String {
|
||||
if emotes.is_empty() {
|
||||
return input.to_string();
|
||||
}
|
||||
|
||||
input
|
||||
.split_whitespace()
|
||||
.map(|word| {
|
||||
if word.len() > 2 && word.starts_with(':') && word.ends_with(':') {
|
||||
let name = &word[1..word.len() - 1];
|
||||
if let Some((id, canonical)) = emotes
|
||||
.iter()
|
||||
.find(|(emote_name, _)| emote_name.eq_ignore_ascii_case(name))
|
||||
{
|
||||
return format!("[emote:{}:{}]", id, canonical);
|
||||
}
|
||||
}
|
||||
word.to_string()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
pub fn profile_from_json(payload: &str) -> Result<KickProfile, AppError> {
|
||||
let value: serde_json::Value = serde_json::from_str(payload)
|
||||
.map_err(|_| AppError::General("Kick kullanıcı yanıtı okunamadı".to_string()))?;
|
||||
|
||||
let user = value.get("user").unwrap_or(&value);
|
||||
let id = user
|
||||
.get("id")
|
||||
.and_then(|v| v.as_i64())
|
||||
.ok_or_else(|| AppError::General("Kick kullanıcı kimliği bulunamadı".to_string()))?;
|
||||
let username = user
|
||||
.get("username")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("kick-user")
|
||||
.to_string();
|
||||
let avatar_url = user
|
||||
.get("profile_pic")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
|
||||
Ok(KickProfile {
|
||||
id,
|
||||
username,
|
||||
avatar_url,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn decodes_percent_encoded_session_token() {
|
||||
assert_eq!(
|
||||
normalize_session_token("%7Cabc%7Cdef%2Bghi%3D"),
|
||||
"|abc|def+ghi="
|
||||
);
|
||||
assert_eq!(normalize_session_token("Bearer 12345%7Ctoken"), "12345|token");
|
||||
assert_eq!(normalize_session_token("\"12345|token\""), "12345|token");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_cookie_header() {
|
||||
let cookies = vec![
|
||||
("session_token".to_string(), "abc".to_string()),
|
||||
("XSRF-TOKEN".to_string(), "xyz".to_string()),
|
||||
];
|
||||
assert_eq!(cookie_header(&cookies), "session_token=abc; XSRF-TOKEN=xyz");
|
||||
assert_eq!(find_cookie(&cookies, "xsrf-token"), Some("xyz"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_emote_shortcuts() {
|
||||
let emotes = vec![
|
||||
("KEKW".to_string(), "KEKW".to_string()),
|
||||
("catJAM".to_string(), "catJAM".to_string()),
|
||||
];
|
||||
assert_eq!(
|
||||
format_emotes("hello :kekw: world", &emotes),
|
||||
"hello [emote:KEKW:KEKW] world"
|
||||
);
|
||||
assert_eq!(format_emotes("plain text", &emotes), "plain text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_profile_payload() {
|
||||
let profile =
|
||||
profile_from_json(r#"{"id": 42, "username": "tester", "profile_pic": "https://x/y.png"}"#)
|
||||
.expect("profile");
|
||||
assert_eq!(profile.id, 42);
|
||||
assert_eq!(profile.username, "tester");
|
||||
assert_eq!(profile.avatar_url, "https://x/y.png");
|
||||
|
||||
let nested = profile_from_json(r#"{"user": {"id": 7, "username": "n"}}"#).expect("nested");
|
||||
assert_eq!(nested.id, 7);
|
||||
}
|
||||
}
|
||||
162
src-tauri/src/services/logging.rs
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
use crate::error::AppError;
|
||||
use log::{Level, LevelFilter, Metadata, Record};
|
||||
use std::collections::VecDeque;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const MAX_LOG_SIZE_BYTES: u64 = 5 * 1024 * 1024; // 5 MB
|
||||
const RING_BUFFER_CAPACITY: usize = 200;
|
||||
|
||||
pub struct AppLogger {
|
||||
file_mutex: Mutex<Option<File>>,
|
||||
log_dir: PathBuf,
|
||||
recent_logs: Mutex<VecDeque<String>>,
|
||||
}
|
||||
|
||||
static LOGGER: Mutex<Option<&'static AppLogger>> = Mutex::new(None);
|
||||
|
||||
impl AppLogger {
|
||||
pub fn init() -> Result<&'static AppLogger, AppError> {
|
||||
let mut dir = dirs::data_local_dir().unwrap_or_else(|| PathBuf::from("."));
|
||||
dir.push("LDKickWatch");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
|
||||
let log_file_path = dir.join("app.log");
|
||||
|
||||
// Rotate if existing log file exceeds max size
|
||||
if let Ok(meta) = fs::metadata(&log_file_path) {
|
||||
if meta.len() > MAX_LOG_SIZE_BYTES {
|
||||
let backup_path = dir.join("app.log.old");
|
||||
let _ = fs::rename(&log_file_path, backup_path);
|
||||
}
|
||||
}
|
||||
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&log_file_path)
|
||||
.ok();
|
||||
|
||||
let logger = Box::leak(Box::new(Self {
|
||||
file_mutex: Mutex::new(file),
|
||||
log_dir: dir,
|
||||
recent_logs: Mutex::new(VecDeque::with_capacity(RING_BUFFER_CAPACITY)),
|
||||
}));
|
||||
|
||||
if log::set_logger(logger).is_ok() {
|
||||
log::set_max_level(LevelFilter::Info);
|
||||
}
|
||||
|
||||
if let Ok(mut global) = LOGGER.lock() {
|
||||
*global = Some(logger);
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"=== LD KickWatch v{} Günlük Kaydı Başlatıldı ===",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
);
|
||||
Ok(logger)
|
||||
}
|
||||
|
||||
pub fn get_instance() -> Option<&'static AppLogger> {
|
||||
LOGGER.lock().ok().and_then(|g| *g)
|
||||
}
|
||||
|
||||
pub fn get_recent_logs(&self) -> Vec<String> {
|
||||
if let Ok(buf) = self.recent_logs.lock() {
|
||||
buf.iter().cloned().collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_logs(&self) -> Result<(), AppError> {
|
||||
if let Ok(mut buf) = self.recent_logs.lock() {
|
||||
buf.clear();
|
||||
}
|
||||
|
||||
let log_file_path = self.log_dir.join("app.log");
|
||||
if let Ok(mut file_guard) = self.file_mutex.lock() {
|
||||
*file_guard = None;
|
||||
let _ = fs::remove_file(&log_file_path);
|
||||
*file_guard = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(&log_file_path)
|
||||
.ok();
|
||||
}
|
||||
|
||||
log::info!("Günlük kayıtları temizlendi.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_log_dir(&self) -> PathBuf {
|
||||
self.log_dir.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl log::Log for AppLogger {
|
||||
fn enabled(&self, metadata: &Metadata) -> bool {
|
||||
metadata.level() <= Level::Info
|
||||
}
|
||||
|
||||
fn log(&self, record: &Record) {
|
||||
if !self.enabled(record.metadata()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
|
||||
let line = format!(
|
||||
"[{}] [{:<5}] [{}] {}\n",
|
||||
now,
|
||||
record.level(),
|
||||
record.target(),
|
||||
record.args()
|
||||
);
|
||||
|
||||
// Update in-memory ring buffer
|
||||
if let Ok(mut buf) = self.recent_logs.lock() {
|
||||
if buf.len() >= RING_BUFFER_CAPACITY {
|
||||
buf.pop_front();
|
||||
}
|
||||
buf.push_back(line.trim_end().to_string());
|
||||
}
|
||||
|
||||
// Write to log file with automatic size rotation
|
||||
if let Ok(mut file_opt) = self.file_mutex.lock() {
|
||||
if let Some(ref mut file) = *file_opt {
|
||||
let _ = file.write_all(line.as_bytes());
|
||||
let _ = file.flush();
|
||||
|
||||
if let Ok(meta) = file.metadata() {
|
||||
if meta.len() > MAX_LOG_SIZE_BYTES {
|
||||
let log_file_path = self.log_dir.join("app.log");
|
||||
let backup_path = self.log_dir.join("app.log.old");
|
||||
drop(file_opt); // Release lock before rename
|
||||
|
||||
if let Ok(mut re_lock) = self.file_mutex.lock() {
|
||||
*re_lock = None;
|
||||
let _ = fs::rename(&log_file_path, backup_path);
|
||||
*re_lock = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&log_file_path)
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {
|
||||
if let Ok(mut file_opt) = self.file_mutex.lock() {
|
||||
if let Some(ref mut file) = *file_opt {
|
||||
let _ = file.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
23
src-tauri/src/services/mod.rs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
pub mod chat;
|
||||
pub mod config;
|
||||
pub mod hls_pipe;
|
||||
pub mod kick_api;
|
||||
pub mod kick_auth;
|
||||
pub mod logging;
|
||||
pub mod mpv_player;
|
||||
pub mod player;
|
||||
pub mod polling;
|
||||
pub mod shortcut;
|
||||
pub mod sound;
|
||||
|
||||
pub use chat::PusherChatService;
|
||||
pub use config::ConfigService;
|
||||
pub use hls_pipe::{HlsPipeSession, PipeMode, PipeStartResult};
|
||||
pub use kick_api::{parse_hls_variants, FollowedChannelEntry, HlsVariant, KickApiService};
|
||||
pub use kick_auth::{KickAuthContext, KickProfile};
|
||||
pub use logging::AppLogger;
|
||||
pub use mpv_player::{sanitize_http_headers, MpvState, MpvStatsEvent};
|
||||
pub use player::{ExternalPlayerOptions, PlayerService};
|
||||
pub use polling::PollingService;
|
||||
pub use shortcut::ShortcutService;
|
||||
pub use sound::SoundService;
|
||||
3545
src-tauri/src/services/mpv_player.rs
Normal file
322
src-tauri/src/services/player.rs
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
use crate::error::AppError;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, Command};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExternalPlayerOptions<'a> {
|
||||
pub channel_name: &'a str,
|
||||
pub player_type: &'a str,
|
||||
pub stream_url: &'a str,
|
||||
pub player_path: Option<&'a str>,
|
||||
pub streamlink_path: Option<&'a str>,
|
||||
pub quality: &'a str,
|
||||
pub extra_args: Option<&'a str>,
|
||||
}
|
||||
|
||||
pub struct PlayerService {
|
||||
active_processes: Arc<Mutex<HashMap<String, Child>>>,
|
||||
}
|
||||
|
||||
impl Default for PlayerService {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate_channel_name(name: &str) -> Result<(), AppError> {
|
||||
let trimmed = name.trim();
|
||||
if trimmed.is_empty() || trimmed.len() > 64 {
|
||||
return Err(AppError::InvalidInput(
|
||||
"Kanal adı geçersiz uzunlukta".to_string(),
|
||||
));
|
||||
}
|
||||
if !trimmed
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
|
||||
{
|
||||
return Err(AppError::InvalidInput(
|
||||
"Kanal adı yalnızca harf, rakam, tire (-) ve alt çizgi (_) içerebilir".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_stream_url(url: &str) -> Result<(), AppError> {
|
||||
let trimmed = url.trim();
|
||||
if !trimmed.starts_with("https://") && !trimmed.starts_with("http://") {
|
||||
return Err(AppError::InvalidInput(
|
||||
"Yayın bağlantısı geçerli bir HTTP/HTTPS URL'si olmalıdır".to_string(),
|
||||
));
|
||||
}
|
||||
if trimmed.contains('\n')
|
||||
|| trimmed.contains('\r')
|
||||
|| trimmed.contains('"')
|
||||
|| trimmed.contains('\'')
|
||||
{
|
||||
return Err(AppError::InvalidInput(
|
||||
"Yayın bağlantısı geçersiz karakterler içeriyor".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn sanitize_extra_args(raw_args: &str) -> Vec<String> {
|
||||
// Dangerous argument tokens that could lead to command execution
|
||||
const BLOCKED_TOKENS: &[&str] = &[
|
||||
"--exec",
|
||||
"--system",
|
||||
"--command",
|
||||
"--hook",
|
||||
"--player-passthrough",
|
||||
"--script",
|
||||
"--input-ipc-server",
|
||||
"--input-unix-socket",
|
||||
"--log-file",
|
||||
"--dump-stats",
|
||||
"--stream-record",
|
||||
"--record-file",
|
||||
"--output",
|
||||
"--sout",
|
||||
"cmd.exe",
|
||||
"powershell",
|
||||
"powershell.exe",
|
||||
"bash",
|
||||
"sh",
|
||||
];
|
||||
|
||||
let mut safe_args = Vec::new();
|
||||
for token in raw_args.split_whitespace() {
|
||||
let lower = token.to_lowercase();
|
||||
let is_blocked = BLOCKED_TOKENS.iter().any(|b| lower.contains(b))
|
||||
|| lower == "-o"
|
||||
|| lower.starts_with("-o=")
|
||||
|| lower == "--o"
|
||||
|| lower.starts_with("--o=");
|
||||
if !is_blocked && !token.contains(';') && !token.contains('&') && !token.contains('|') {
|
||||
safe_args.push(token.to_string());
|
||||
} else {
|
||||
log::warn!(
|
||||
"Güvenlik filtresi tarafından engellenen oynatıcı argümanı: {}",
|
||||
token
|
||||
);
|
||||
}
|
||||
}
|
||||
safe_args
|
||||
}
|
||||
|
||||
impl PlayerService {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
active_processes: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_vlc(&self, configured_path: Option<&str>) -> Option<String> {
|
||||
if let Some(cfg) = configured_path {
|
||||
if !cfg.trim().is_empty() && Path::new(cfg).exists() {
|
||||
return Some(cfg.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let candidates = [
|
||||
r"C:\Program Files\VideoLAN\VLC\vlc.exe",
|
||||
r"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe",
|
||||
];
|
||||
|
||||
for path in &candidates {
|
||||
if Path::new(path).exists() {
|
||||
return Some(path.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Self::find_in_path("vlc.exe")
|
||||
}
|
||||
|
||||
pub fn find_mpv(&self, configured_path: Option<&str>) -> Option<String> {
|
||||
if let Some(cfg) = configured_path {
|
||||
if !cfg.trim().is_empty() && Path::new(cfg).exists() {
|
||||
return Some(cfg.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let candidates = [
|
||||
r"C:\Program Files\mpv\mpv.exe",
|
||||
r"C:\Program Files (x86)\mpv\mpv.exe",
|
||||
];
|
||||
|
||||
for path in &candidates {
|
||||
if Path::new(path).exists() {
|
||||
return Some(path.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Self::find_in_path("mpv.exe")
|
||||
}
|
||||
|
||||
pub fn find_streamlink(&self, configured_path: Option<&str>) -> Option<String> {
|
||||
if let Some(cfg) = configured_path {
|
||||
if !cfg.trim().is_empty() && Path::new(cfg).exists() {
|
||||
return Some(cfg.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let candidates = [
|
||||
r"C:\Program Files\Streamlink\bin\streamlink.exe",
|
||||
r"C:\Program Files (x86)\Streamlink\bin\streamlink.exe",
|
||||
];
|
||||
|
||||
for path in &candidates {
|
||||
if Path::new(path).exists() {
|
||||
return Some(path.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Self::find_in_path("streamlink.exe")
|
||||
}
|
||||
|
||||
fn find_in_path(binary_name: &str) -> Option<String> {
|
||||
let path_var = std::env::var("PATH").ok()?;
|
||||
for dir in std::env::split_paths(&path_var) {
|
||||
let full = dir.join(binary_name);
|
||||
if full.exists() {
|
||||
return Some(full.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn is_playing(&self, channel_name: &str) -> bool {
|
||||
let mut map = match self.active_processes.lock() {
|
||||
Ok(m) => m,
|
||||
Err(_) => return false,
|
||||
};
|
||||
|
||||
if let Some(child) = map.get_mut(channel_name) {
|
||||
match child.try_wait() {
|
||||
Ok(None) => true,
|
||||
_ => {
|
||||
map.remove(channel_name);
|
||||
false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn play_external(&self, opts: ExternalPlayerOptions<'_>) -> Result<String, AppError> {
|
||||
validate_channel_name(opts.channel_name)?;
|
||||
validate_stream_url(opts.stream_url)?;
|
||||
|
||||
self.stop(opts.channel_name);
|
||||
|
||||
let sanitized_args = opts.extra_args.map(sanitize_extra_args).unwrap_or_default();
|
||||
|
||||
let child = if opts.player_type.eq_ignore_ascii_case("streamlink") {
|
||||
let sl_path = self
|
||||
.find_streamlink(opts.streamlink_path)
|
||||
.ok_or_else(|| AppError::PlayerNotFound("Streamlink bulunamadı".to_string()))?;
|
||||
let player_bin = self
|
||||
.find_vlc(opts.player_path)
|
||||
.or_else(|| self.find_mpv(opts.player_path))
|
||||
.unwrap_or_else(|| "vlc".to_string());
|
||||
|
||||
let mut cmd = Command::new(sl_path);
|
||||
let kick_page = format!("https://kick.com/{}", opts.channel_name);
|
||||
cmd.arg(&kick_page)
|
||||
.arg(opts.quality)
|
||||
.arg("--player")
|
||||
.arg(&player_bin)
|
||||
.arg("--title")
|
||||
.arg(format!("{} - LD KickWatch", opts.channel_name));
|
||||
|
||||
for arg in sanitized_args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
cmd.spawn().map_err(AppError::Io)?
|
||||
} else if opts.player_type.eq_ignore_ascii_case("mpv") {
|
||||
let bin = self
|
||||
.find_mpv(opts.player_path)
|
||||
.ok_or_else(|| AppError::PlayerNotFound("MPV Player bulunamadı".to_string()))?;
|
||||
|
||||
let mut cmd = Command::new(bin);
|
||||
cmd.arg(format!("--title={} - LD KickWatch", opts.channel_name));
|
||||
|
||||
for arg in sanitized_args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
// "--" stops option processing in MPV to prevent flag injection
|
||||
cmd.arg("--").arg(opts.stream_url);
|
||||
|
||||
cmd.spawn().map_err(AppError::Io)?
|
||||
} else {
|
||||
// Default: VLC
|
||||
let bin = self.find_vlc(opts.player_path).ok_or_else(|| {
|
||||
AppError::PlayerNotFound("VLC Media Player bulunamadı".to_string())
|
||||
})?;
|
||||
|
||||
let mut cmd = Command::new(bin);
|
||||
cmd.arg("--no-video-title-show")
|
||||
.arg("--network-caching=800")
|
||||
.arg(format!("--meta-title={} - LD KickWatch", opts.channel_name));
|
||||
|
||||
for arg in sanitized_args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
// "--" stops option processing in VLC
|
||||
cmd.arg("--").arg(opts.stream_url);
|
||||
|
||||
cmd.spawn().map_err(AppError::Io)?
|
||||
};
|
||||
|
||||
if let Ok(mut map) = self.active_processes.lock() {
|
||||
map.insert(opts.channel_name.to_lowercase(), child);
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"Harici oynatıcı başlatıldı: kanal={}, oynatıcı={}",
|
||||
opts.channel_name,
|
||||
opts.player_type
|
||||
);
|
||||
Ok(format!(
|
||||
"{} yayını harici oynatıcıda başlatıldı.",
|
||||
opts.channel_name
|
||||
))
|
||||
}
|
||||
|
||||
pub fn stop(&self, channel_name: &str) {
|
||||
if let Ok(mut map) = self.active_processes.lock() {
|
||||
if let Some(child) = map.remove(&channel_name.to_lowercase()) {
|
||||
Self::kill_process(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stop_all(&self) {
|
||||
if let Ok(mut map) = self.active_processes.lock() {
|
||||
for (_, child) in map.drain() {
|
||||
Self::kill_process(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kill_process(mut child: Child) {
|
||||
let pid = child.id();
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
let _ = Command::new("taskkill")
|
||||
.args(["/PID", &pid.to_string(), "/T", "/F"])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output();
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
860
src-tauri/src/services/polling.rs
Normal file
|
|
@ -0,0 +1,860 @@
|
|||
use crate::error::AppError;
|
||||
use crate::models::{AppConfig, ChannelCard, KickChannelResponse};
|
||||
use crate::services::config::ConfigService;
|
||||
use crate::services::kick_api::{FollowedChannelEntry, KickApiService};
|
||||
use crate::services::kick_auth::KickAuthContext;
|
||||
use crate::services::sound::SoundService;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
|
||||
fn normalize_slug(raw: &str) -> String {
|
||||
let compact: String = raw.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
compact
|
||||
.trim_start_matches('@')
|
||||
.trim_start_matches("https://kick.com/")
|
||||
.trim_start_matches("http://kick.com/")
|
||||
.trim_start_matches("https://www.kick.com/")
|
||||
.trim_start_matches("kick.com/")
|
||||
.trim_end_matches('/')
|
||||
.to_lowercase()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PollContext {
|
||||
pub app_handle: AppHandle,
|
||||
pub api: Arc<KickApiService>,
|
||||
pub config: Arc<RwLock<AppConfig>>,
|
||||
pub config_service: Arc<ConfigService>,
|
||||
pub prev_states: Arc<Mutex<HashMap<String, ChannelCard>>>,
|
||||
pub followed_only_cards: Arc<RwLock<Vec<ChannelCard>>>,
|
||||
pub poll_lock: Arc<Mutex<()>>,
|
||||
pub last_poll_completed: Arc<Mutex<Option<Instant>>>,
|
||||
pub has_completed_initial_poll: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
pub struct PollingService {
|
||||
is_running: Arc<AtomicBool>,
|
||||
pub ctx: PollContext,
|
||||
pub prev_states: Arc<Mutex<HashMap<String, ChannelCard>>>,
|
||||
}
|
||||
|
||||
impl PollingService {
|
||||
pub fn new(
|
||||
app_handle: AppHandle,
|
||||
api: Arc<KickApiService>,
|
||||
config: Arc<RwLock<AppConfig>>,
|
||||
config_service: Arc<ConfigService>,
|
||||
) -> Self {
|
||||
let is_authed = !config.blocking_read().kick_token.trim().is_empty();
|
||||
let initial_cards = if is_authed {
|
||||
config_service.load_followed_cache()
|
||||
} else {
|
||||
config_service.load_channel_cache()
|
||||
};
|
||||
|
||||
let mut initial_map = HashMap::new();
|
||||
let mut followed_list = Vec::new();
|
||||
for mut card in initial_cards {
|
||||
let clean = normalize_slug(&card.channel_name);
|
||||
if !clean.is_empty() {
|
||||
card.channel_name = clean.clone();
|
||||
card.is_playing = false;
|
||||
if is_authed {
|
||||
followed_list.push(card.clone());
|
||||
}
|
||||
initial_map.insert(clean, card);
|
||||
}
|
||||
}
|
||||
|
||||
let prev_states = Arc::new(Mutex::new(initial_map));
|
||||
let ctx = PollContext {
|
||||
app_handle,
|
||||
api,
|
||||
config,
|
||||
config_service,
|
||||
prev_states: Arc::clone(&prev_states),
|
||||
followed_only_cards: Arc::new(RwLock::new(followed_list)),
|
||||
poll_lock: Arc::new(Mutex::new(())),
|
||||
last_poll_completed: Arc::new(Mutex::new(None)),
|
||||
has_completed_initial_poll: Arc::new(AtomicBool::new(false)),
|
||||
};
|
||||
|
||||
Self {
|
||||
is_running: Arc::new(AtomicBool::new(false)),
|
||||
ctx,
|
||||
prev_states,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn context(&self) -> PollContext {
|
||||
self.ctx.clone()
|
||||
}
|
||||
|
||||
pub fn start(&self) {
|
||||
if self.is_running.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
|
||||
let ctx = self.ctx.clone();
|
||||
let is_running = Arc::clone(&self.is_running);
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while is_running.load(Ordering::SeqCst) {
|
||||
let interval_secs = {
|
||||
let cfg = ctx.config.read().await;
|
||||
cfg.refresh_interval_seconds.max(15)
|
||||
};
|
||||
|
||||
let _ = ctx.poll_now().await;
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(interval_secs)).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn stop(&self) {
|
||||
self.is_running.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub async fn get_cached_or_placeholder_cards(&self) -> Vec<ChannelCard> {
|
||||
self.ctx.get_cached_or_placeholder_cards().await
|
||||
}
|
||||
|
||||
pub async fn invalidate_cooldown(&self) {
|
||||
self.ctx.invalidate_cooldown().await;
|
||||
}
|
||||
|
||||
pub async fn poll_now(&self) -> Vec<ChannelCard> {
|
||||
self.ctx.poll_now().await
|
||||
}
|
||||
|
||||
pub async fn apply_followed_entries(
|
||||
&self,
|
||||
entries: &[FollowedChannelEntry],
|
||||
emit_live_ready: bool,
|
||||
is_complete_list: bool,
|
||||
) -> Vec<ChannelCard> {
|
||||
self.ctx
|
||||
.apply_followed_entries(entries, emit_live_ready, is_complete_list)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn remove_followed_channel(&self, slug: &str) {
|
||||
self.ctx.remove_followed_channel(slug).await;
|
||||
}
|
||||
|
||||
pub async fn upsert_followed_channel(&self, slug: &str) {
|
||||
self.ctx.upsert_followed_channel(slug).await;
|
||||
}
|
||||
|
||||
pub async fn clear_all_cached_channels(&self) {
|
||||
self.ctx.clear_all_cached_channels().await;
|
||||
}
|
||||
|
||||
pub async fn sync_cache_from_config(&self) {
|
||||
let (is_authed, channel_groups) = {
|
||||
let cfg = self.config_service_read_sync().await;
|
||||
(!cfg.0.trim().is_empty(), cfg.1)
|
||||
};
|
||||
|
||||
if is_authed {
|
||||
let updated: Vec<ChannelCard> = {
|
||||
let mut list = self.ctx.followed_only_cards.write().await;
|
||||
for card in list.iter_mut() {
|
||||
let clean = normalize_slug(&card.channel_name);
|
||||
card.group_name = channel_groups.get(&clean).cloned();
|
||||
}
|
||||
list.clone()
|
||||
};
|
||||
self.ctx.config_service.save_followed_cache(&updated);
|
||||
let _ = self.ctx.app_handle.emit("channels-updated", &updated);
|
||||
return;
|
||||
}
|
||||
|
||||
let cards = self.ctx.get_cached_or_placeholder_cards().await;
|
||||
{
|
||||
let mut prev = self.ctx.prev_states.lock().await;
|
||||
let keep: HashSet<String> = cards.iter().map(|c| c.channel_name.clone()).collect();
|
||||
prev.retain(|k, _| keep.contains(k));
|
||||
for c in &cards {
|
||||
prev.insert(c.channel_name.clone(), c.clone());
|
||||
}
|
||||
}
|
||||
self.ctx.config_service.save_channel_cache(&cards);
|
||||
}
|
||||
|
||||
async fn config_service_read_sync(&self) -> (String, HashMap<String, String>) {
|
||||
let cfg = self.ctx.config.read().await;
|
||||
(cfg.kick_token.clone(), cfg.channel_groups.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl PollContext {
|
||||
pub async fn invalidate_cooldown(&self) {
|
||||
*self.last_poll_completed.lock().await = None;
|
||||
}
|
||||
|
||||
pub async fn get_cached_or_placeholder_cards(&self) -> Vec<ChannelCard> {
|
||||
let (kick_token, favorites, channel_groups) = {
|
||||
let cfg = self.config.read().await;
|
||||
(
|
||||
cfg.kick_token.clone(),
|
||||
cfg.favorites.clone(),
|
||||
cfg.channel_groups.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
// Logged-in mode strictly returns cached Kick followed channels only
|
||||
if !kick_token.trim().is_empty() {
|
||||
let followed = self.followed_only_cards.read().await;
|
||||
return followed
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let clean = normalize_slug(&c.channel_name);
|
||||
let mut cloned = c.clone();
|
||||
cloned.group_name = channel_groups
|
||||
.get(&clean)
|
||||
.or_else(|| channel_groups.get(&c.channel_name))
|
||||
.cloned();
|
||||
cloned
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
let prev = self.prev_states.lock().await;
|
||||
let mut seen = HashSet::new();
|
||||
let mut cards = Vec::with_capacity(favorites.len());
|
||||
|
||||
for fav in favorites {
|
||||
let clean = normalize_slug(&fav);
|
||||
if clean.is_empty() || !seen.insert(clean.clone()) {
|
||||
continue;
|
||||
}
|
||||
let grp = channel_groups
|
||||
.get(&clean)
|
||||
.or_else(|| channel_groups.get(&fav))
|
||||
.cloned();
|
||||
if let Some(cached) = prev.get(&clean) {
|
||||
let mut cloned = cached.clone();
|
||||
cloned.group_name = grp;
|
||||
cards.push(cloned);
|
||||
} else {
|
||||
cards.push(ChannelCard::new_offline(clean, grp));
|
||||
}
|
||||
}
|
||||
|
||||
cards
|
||||
}
|
||||
|
||||
pub async fn apply_followed_entries(
|
||||
&self,
|
||||
entries: &[FollowedChannelEntry],
|
||||
emit_live_ready: bool,
|
||||
is_complete_list: bool,
|
||||
) -> Vec<ChannelCard> {
|
||||
let channel_groups = {
|
||||
let cfg = self.config.read().await;
|
||||
cfg.channel_groups.clone()
|
||||
};
|
||||
|
||||
let mut prev = self.prev_states.lock().await;
|
||||
let mut seen = HashSet::new();
|
||||
let mut cards = Vec::with_capacity(entries.len());
|
||||
|
||||
for entry in entries {
|
||||
if entry.channel_slug.is_empty() || !seen.insert(entry.channel_slug.clone()) {
|
||||
continue;
|
||||
}
|
||||
let grp = channel_groups.get(&entry.channel_slug).cloned();
|
||||
let card = card_from_followed_entry(entry, grp, prev.get(&entry.channel_slug));
|
||||
prev.insert(entry.channel_slug.clone(), card.clone());
|
||||
cards.push(card);
|
||||
}
|
||||
|
||||
if is_complete_list {
|
||||
prev.retain(|k, _| seen.contains(k));
|
||||
} else {
|
||||
let existing = self.followed_only_cards.read().await;
|
||||
for cached in existing.iter() {
|
||||
let clean = normalize_slug(&cached.channel_name);
|
||||
if !clean.is_empty() && seen.insert(clean.clone()) {
|
||||
let mut cloned = cached.clone();
|
||||
cloned.group_name = channel_groups.get(&clean).cloned();
|
||||
cards.push(cloned);
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(prev);
|
||||
|
||||
{
|
||||
let mut list = self.followed_only_cards.write().await;
|
||||
*list = cards.clone();
|
||||
}
|
||||
|
||||
if is_complete_list {
|
||||
self.config_service.save_followed_cache(&cards);
|
||||
}
|
||||
if emit_live_ready {
|
||||
let _ = self.app_handle.emit("channels:live-ready", &cards);
|
||||
}
|
||||
let _ = self.app_handle.emit("channels-updated", &cards);
|
||||
cards
|
||||
}
|
||||
|
||||
pub async fn remove_followed_channel(&self, slug: &str) {
|
||||
let clean = normalize_slug(slug);
|
||||
let updated: Vec<ChannelCard> = {
|
||||
let mut list = self.followed_only_cards.write().await;
|
||||
list.retain(|c| normalize_slug(&c.channel_name) != clean);
|
||||
list.clone()
|
||||
};
|
||||
{
|
||||
let mut prev = self.prev_states.lock().await;
|
||||
prev.remove(&clean);
|
||||
}
|
||||
self.config_service.save_followed_cache(&updated);
|
||||
let _ = self.app_handle.emit("channels-updated", &updated);
|
||||
}
|
||||
|
||||
pub async fn upsert_followed_channel(&self, slug: &str) {
|
||||
let clean = normalize_slug(slug);
|
||||
if clean.is_empty() {
|
||||
return;
|
||||
}
|
||||
let group_name = {
|
||||
let cfg = self.config.read().await;
|
||||
cfg.channel_groups.get(&clean).cloned()
|
||||
};
|
||||
let card = match self.api.get_channel(&clean).await {
|
||||
Ok(data) => map_response_to_card(clean.clone(), data, group_name),
|
||||
Err(_) => ChannelCard::new_offline(clean.clone(), group_name),
|
||||
};
|
||||
let updated = {
|
||||
let mut list = self.followed_only_cards.write().await;
|
||||
if let Some(slot) = list
|
||||
.iter_mut()
|
||||
.find(|c| normalize_slug(&c.channel_name) == clean)
|
||||
{
|
||||
*slot = card.clone();
|
||||
} else {
|
||||
list.push(card.clone());
|
||||
}
|
||||
list.sort_by(|a, b| {
|
||||
b.is_live
|
||||
.cmp(&a.is_live)
|
||||
.then_with(|| b.viewers.cmp(&a.viewers))
|
||||
.then_with(|| a.channel_name.cmp(&b.channel_name))
|
||||
});
|
||||
list.clone()
|
||||
};
|
||||
{
|
||||
let mut prev = self.prev_states.lock().await;
|
||||
prev.insert(clean, card);
|
||||
}
|
||||
self.config_service.save_followed_cache(&updated);
|
||||
let _ = self.app_handle.emit("channels-updated", &updated);
|
||||
}
|
||||
|
||||
pub async fn clear_all_cached_channels(&self) {
|
||||
self.followed_only_cards.write().await.clear();
|
||||
self.prev_states.lock().await.clear();
|
||||
*self.last_poll_completed.lock().await = None;
|
||||
self.has_completed_initial_poll
|
||||
.store(false, Ordering::SeqCst);
|
||||
let empty: Vec<ChannelCard> = Vec::new();
|
||||
let _ = self.app_handle.emit("channels:live-ready", &empty);
|
||||
let _ = self.app_handle.emit("channels-updated", &empty);
|
||||
}
|
||||
|
||||
pub async fn poll_now(&self) -> Vec<ChannelCard> {
|
||||
let _poll_guard = self.poll_lock.lock().await;
|
||||
if let Some(last) = *self.last_poll_completed.lock().await {
|
||||
if last.elapsed() < Duration::from_millis(1500) {
|
||||
return self.get_cached_or_placeholder_cards().await;
|
||||
}
|
||||
}
|
||||
|
||||
let (
|
||||
favorites,
|
||||
channel_groups,
|
||||
notifications_enabled,
|
||||
sound_enabled,
|
||||
custom_sound,
|
||||
notify_cat,
|
||||
keywords,
|
||||
kick_token,
|
||||
kick_cookies,
|
||||
kick_xsrf,
|
||||
kick_user_agent,
|
||||
) = {
|
||||
let cfg = self.config.read().await;
|
||||
(
|
||||
cfg.favorites.clone(),
|
||||
cfg.channel_groups.clone(),
|
||||
cfg.notifications_enabled,
|
||||
cfg.sound_notifications_enabled,
|
||||
cfg.custom_sound_path.clone(),
|
||||
cfg.notify_on_category_change,
|
||||
cfg.alert_keywords.clone(),
|
||||
cfg.kick_token.clone(),
|
||||
cfg.kick_cookies.clone(),
|
||||
cfg.kick_xsrf.clone(),
|
||||
cfg.kick_user_agent.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
let is_authed = !kick_token.trim().is_empty();
|
||||
let prev_snapshot = self.prev_states.lock().await.clone();
|
||||
|
||||
// Authenticated mode: `/api/v2/channels/followed` is the Single Source of Truth.
|
||||
// Never mix default_favorites or unfollowed channels from config.json.
|
||||
if is_authed {
|
||||
let auth = KickAuthContext {
|
||||
token: kick_token,
|
||||
cookie_header: kick_cookies,
|
||||
xsrf_token: kick_xsrf,
|
||||
user_agent: kick_user_agent,
|
||||
};
|
||||
|
||||
match self.api.fetch_followed_live_batch(&auth).await {
|
||||
Ok((mut all_followed, next_cursor, all_done)) => {
|
||||
let cached_followed = self.followed_only_cards.read().await.clone();
|
||||
|
||||
// Stage 1: emit live followed channels immediately (<500ms)
|
||||
let mut stage1_seen = HashSet::new();
|
||||
let mut stage1_cards = Vec::with_capacity(all_followed.len());
|
||||
for entry in &all_followed {
|
||||
if stage1_seen.insert(entry.channel_slug.clone()) {
|
||||
let grp = channel_groups.get(&entry.channel_slug).cloned();
|
||||
stage1_cards.push(card_from_followed_entry(
|
||||
entry,
|
||||
grp,
|
||||
prev_snapshot.get(&entry.channel_slug),
|
||||
));
|
||||
}
|
||||
}
|
||||
for cached in &cached_followed {
|
||||
let clean = normalize_slug(&cached.channel_name);
|
||||
if !clean.is_empty() && stage1_seen.insert(clean.clone()) {
|
||||
let mut cloned = cached.clone();
|
||||
cloned.group_name = channel_groups.get(&clean).cloned();
|
||||
stage1_cards.push(cloned);
|
||||
}
|
||||
}
|
||||
let _ = self.app_handle.emit("channels:live-ready", &stage1_cards);
|
||||
let _ = self.app_handle.emit("channels-updated", &stage1_cards);
|
||||
|
||||
// Stage 2: collect all remaining followed pages and build authoritative list
|
||||
if !all_done {
|
||||
if let Some(cursor) = next_cursor {
|
||||
let rest = self.api.fetch_followed_remaining(&auth, cursor, 500).await;
|
||||
let mut seen_slugs: HashSet<String> = all_followed
|
||||
.iter()
|
||||
.map(|e| e.channel_slug.clone())
|
||||
.collect();
|
||||
for entry in rest {
|
||||
if seen_slugs.insert(entry.channel_slug.clone()) {
|
||||
all_followed.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut final_seen = HashSet::new();
|
||||
let mut results = Vec::with_capacity(all_followed.len());
|
||||
for entry in &all_followed {
|
||||
if final_seen.insert(entry.channel_slug.clone()) {
|
||||
let grp = channel_groups.get(&entry.channel_slug).cloned();
|
||||
results.push(card_from_followed_entry(
|
||||
entry,
|
||||
grp,
|
||||
prev_snapshot.get(&entry.channel_slug),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Keep local config.favorites strictly synchronized with Kick followed list
|
||||
let new_favs: Vec<String> =
|
||||
results.iter().map(|c| c.channel_name.clone()).collect();
|
||||
let fav_set: HashSet<String> = new_favs.iter().cloned().collect();
|
||||
{
|
||||
let mut cfg = self.config.write().await;
|
||||
if cfg.favorites != new_favs {
|
||||
cfg.favorites = new_favs;
|
||||
cfg.channel_groups
|
||||
.retain(|k, _| fav_set.contains(&normalize_slug(k)));
|
||||
let _ = self.config_service.save(&cfg);
|
||||
}
|
||||
}
|
||||
|
||||
self.finalize_poll(
|
||||
&results,
|
||||
&prev_snapshot,
|
||||
false,
|
||||
notifications_enabled,
|
||||
sound_enabled,
|
||||
&custom_sound,
|
||||
notify_cat,
|
||||
&keywords,
|
||||
)
|
||||
.await;
|
||||
|
||||
*self.followed_only_cards.write().await = results.clone();
|
||||
self.config_service.save_followed_cache(&results);
|
||||
let _ = self.app_handle.emit("channels-updated", &results);
|
||||
*self.last_poll_completed.lock().await = Some(Instant::now());
|
||||
return results;
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!("Takip edilen kanallar toplu alınamadı: {}", err);
|
||||
let preserved: Vec<ChannelCard> = self
|
||||
.followed_only_cards
|
||||
.read()
|
||||
.await
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let clean = normalize_slug(&c.channel_name);
|
||||
let mut cloned = c.clone();
|
||||
cloned.group_name = channel_groups.get(&clean).cloned();
|
||||
cloned
|
||||
})
|
||||
.collect();
|
||||
let _ = self.app_handle.emit("channels:live-ready", &preserved);
|
||||
let _ = self.app_handle.emit("channels-updated", &preserved);
|
||||
*self.last_poll_completed.lock().await = Some(Instant::now());
|
||||
return preserved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Guest mode: priority-partitioned parallel `curl --parallel` on user favorites
|
||||
let mut clean_favorites: Vec<(String, Option<String>)> = Vec::with_capacity(favorites.len());
|
||||
let mut seen = HashSet::new();
|
||||
for raw in favorites {
|
||||
let clean = normalize_slug(&raw);
|
||||
if clean.is_empty() || !seen.insert(clean.clone()) {
|
||||
continue;
|
||||
}
|
||||
let grp = channel_groups
|
||||
.get(&clean)
|
||||
.or_else(|| channel_groups.get(&raw))
|
||||
.cloned();
|
||||
clean_favorites.push((clean, grp));
|
||||
}
|
||||
|
||||
if clean_favorites.is_empty() {
|
||||
let empty: Vec<ChannelCard> = Vec::new();
|
||||
self.prev_states.lock().await.clear();
|
||||
self.config_service.save_channel_cache(&empty);
|
||||
let _ = self.app_handle.emit("channels:live-ready", &empty);
|
||||
let _ = self.app_handle.emit("channels-updated", &empty);
|
||||
*self.last_poll_completed.lock().await = Some(Instant::now());
|
||||
return empty;
|
||||
}
|
||||
|
||||
let total_channels = clean_favorites.len();
|
||||
let mut priority_slugs = Vec::new();
|
||||
let mut deferred_slugs = Vec::new();
|
||||
for (slug, _) in &clean_favorites {
|
||||
if prev_snapshot.get(slug).map(|c| c.is_live).unwrap_or(false) {
|
||||
priority_slugs.push(slug.clone());
|
||||
} else {
|
||||
deferred_slugs.push(slug.clone());
|
||||
}
|
||||
}
|
||||
if priority_slugs.is_empty() {
|
||||
let take_n = deferred_slugs.len().min(12);
|
||||
priority_slugs = deferred_slugs.drain(..take_n).collect();
|
||||
}
|
||||
|
||||
let mut stage1_emitted = false;
|
||||
let mut combined = self.api.get_channels_batch(&priority_slugs).await;
|
||||
if !deferred_slugs.is_empty() {
|
||||
let stage1_cards: Vec<ChannelCard> = clean_favorites
|
||||
.iter()
|
||||
.map(|(slug, grp)| match combined.get(slug) {
|
||||
Some(Ok(resp)) => map_response_to_card(slug.clone(), resp.clone(), grp.clone()),
|
||||
_ => prev_snapshot
|
||||
.get(slug)
|
||||
.cloned()
|
||||
.map(|mut c| {
|
||||
c.group_name = grp.clone();
|
||||
c
|
||||
})
|
||||
.unwrap_or_else(|| ChannelCard::new_offline(slug.clone(), grp.clone())),
|
||||
})
|
||||
.collect();
|
||||
let _ = self.app_handle.emit("channels:live-ready", &stage1_cards);
|
||||
let _ = self.app_handle.emit("channels-updated", &stage1_cards);
|
||||
stage1_emitted = true;
|
||||
|
||||
let rest = self.api.get_channels_batch(&deferred_slugs).await;
|
||||
combined.extend(rest);
|
||||
}
|
||||
|
||||
let mut network_error_count = 0usize;
|
||||
let mut results = Vec::with_capacity(total_channels);
|
||||
for (slug, grp) in &clean_favorites {
|
||||
match combined.remove(slug) {
|
||||
Some(Ok(resp)) => {
|
||||
results.push(map_response_to_card(slug.clone(), resp, grp.clone()));
|
||||
}
|
||||
Some(Err(AppError::Network(_))) => {
|
||||
network_error_count += 1;
|
||||
if let Some(old) = prev_snapshot.get(slug) {
|
||||
let mut cloned = old.clone();
|
||||
cloned.group_name = grp.clone();
|
||||
results.push(cloned);
|
||||
} else {
|
||||
results.push(ChannelCard::new_offline(slug.clone(), grp.clone()));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
results.push(ChannelCard::new_offline(slug.clone(), grp.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let is_major_outage = total_channels > 1 && network_error_count >= (total_channels * 3 / 4);
|
||||
if is_major_outage {
|
||||
log::warn!(
|
||||
"Genel ağ kesintisi algılandı ({}/{} kanal hata aldı). Bildirim fırtınası bastırıldı.",
|
||||
network_error_count,
|
||||
total_channels
|
||||
);
|
||||
}
|
||||
|
||||
self.finalize_poll(
|
||||
&results,
|
||||
&prev_snapshot,
|
||||
is_major_outage,
|
||||
notifications_enabled,
|
||||
sound_enabled,
|
||||
&custom_sound,
|
||||
notify_cat,
|
||||
&keywords,
|
||||
)
|
||||
.await;
|
||||
|
||||
if !is_major_outage {
|
||||
self.config_service.save_channel_cache(&results);
|
||||
}
|
||||
if !stage1_emitted {
|
||||
let _ = self.app_handle.emit("channels:live-ready", &results);
|
||||
}
|
||||
let _ = self.app_handle.emit("channels-updated", &results);
|
||||
*self.last_poll_completed.lock().await = Some(Instant::now());
|
||||
results
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn finalize_poll(
|
||||
&self,
|
||||
results: &[ChannelCard],
|
||||
prev_snapshot: &HashMap<String, ChannelCard>,
|
||||
is_major_outage: bool,
|
||||
notifications_enabled: bool,
|
||||
sound_enabled: bool,
|
||||
custom_sound: &str,
|
||||
notify_cat: bool,
|
||||
keywords: &str,
|
||||
) {
|
||||
let allow_notifications = self.has_completed_initial_poll.swap(true, Ordering::SeqCst);
|
||||
if is_major_outage {
|
||||
return;
|
||||
}
|
||||
|
||||
let keyword_list: Vec<String> = keywords
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_lowercase())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
|
||||
let mut prev = self.prev_states.lock().await;
|
||||
let current_slugs: HashSet<String> =
|
||||
results.iter().map(|c| c.channel_name.clone()).collect();
|
||||
prev.retain(|k, _| current_slugs.contains(k));
|
||||
|
||||
for current in results {
|
||||
let name = ¤t.channel_name;
|
||||
if allow_notifications {
|
||||
if let Some(old) = prev_snapshot.get(name) {
|
||||
if !old.is_live && current.is_live {
|
||||
log::info!("Kanal canlı yayına başladı: {}", name);
|
||||
if notifications_enabled {
|
||||
let _ = self.app_handle.emit(
|
||||
"desktop-notification",
|
||||
serde_json::json!({
|
||||
"title": format!("{} Yayında!", name.to_uppercase()),
|
||||
"body": format!("{}: {}", current.category, current.title)
|
||||
}),
|
||||
);
|
||||
}
|
||||
if sound_enabled {
|
||||
let custom_opt = if custom_sound.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(custom_sound)
|
||||
};
|
||||
let _ = SoundService::play_notification(custom_opt, false);
|
||||
}
|
||||
} else if old.is_live && current.is_live {
|
||||
if notify_cat
|
||||
&& !old.category.is_empty()
|
||||
&& old.category != current.category
|
||||
{
|
||||
log::info!(
|
||||
"Kanal kategori değiştirdi: {} -> {}",
|
||||
name,
|
||||
current.category
|
||||
);
|
||||
if notifications_enabled {
|
||||
let _ = self.app_handle.emit(
|
||||
"desktop-notification",
|
||||
serde_json::json!({
|
||||
"title": format!("{} Kategori Değiştirdi", name),
|
||||
"body": format!("Yeni Kategori: {}", current.category)
|
||||
}),
|
||||
);
|
||||
}
|
||||
if sound_enabled {
|
||||
let custom_opt = if custom_sound.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(custom_sound)
|
||||
};
|
||||
let _ = SoundService::play_notification(custom_opt, true);
|
||||
}
|
||||
}
|
||||
|
||||
if !keyword_list.is_empty() && old.title != current.title {
|
||||
let title_lower = current.title.to_lowercase();
|
||||
let cat_lower = current.category.to_lowercase();
|
||||
let matched = keyword_list
|
||||
.iter()
|
||||
.find(|&kw| title_lower.contains(kw) || cat_lower.contains(kw));
|
||||
|
||||
if let Some(kw) = matched {
|
||||
log::info!(
|
||||
"Anahtar kelime yakalandı: kanal={}, kelime={}",
|
||||
name,
|
||||
kw
|
||||
);
|
||||
if notifications_enabled {
|
||||
let _ = self.app_handle.emit(
|
||||
"desktop-notification",
|
||||
serde_json::json!({
|
||||
"title": format!("🎯 Anahtar Kelime Yakalandı: {}", kw),
|
||||
"body": format!("{}: {}", name, current.title)
|
||||
}),
|
||||
);
|
||||
}
|
||||
if sound_enabled {
|
||||
let custom_opt = if custom_sound.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(custom_sound)
|
||||
};
|
||||
let _ = SoundService::play_notification(custom_opt, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
prev.insert(name.clone(), current.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn card_from_followed_entry(
|
||||
entry: &FollowedChannelEntry,
|
||||
group_name: Option<String>,
|
||||
prev: Option<&ChannelCard>,
|
||||
) -> ChannelCard {
|
||||
let avatar_url = if !entry.avatar_url.is_empty() {
|
||||
entry.avatar_url.clone()
|
||||
} else {
|
||||
prev.map(|p| p.avatar_url.clone()).unwrap_or_default()
|
||||
};
|
||||
|
||||
let started_at = if entry.is_live {
|
||||
entry
|
||||
.started_at
|
||||
.clone()
|
||||
.or_else(|| prev.filter(|p| p.is_live).and_then(|p| p.started_at.clone()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
ChannelCard {
|
||||
channel_name: entry.channel_slug.clone(),
|
||||
is_live: entry.is_live,
|
||||
title: if entry.is_live {
|
||||
entry.title.clone()
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
category: if entry.is_live {
|
||||
entry.category.clone()
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
viewers: if entry.is_live { entry.viewers } else { 0 },
|
||||
verified: prev.map(|p| p.verified).unwrap_or(false),
|
||||
avatar_url,
|
||||
group_name,
|
||||
is_playing: false,
|
||||
chatroom_id: prev.and_then(|p| p.chatroom_id),
|
||||
playback_url: prev.and_then(|p| p.playback_url.clone()),
|
||||
thumbnail_url: prev.and_then(|p| p.thumbnail_url.clone()),
|
||||
started_at,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_response_to_card(
|
||||
channel_name: String,
|
||||
data: KickChannelResponse,
|
||||
group_name: Option<String>,
|
||||
) -> ChannelCard {
|
||||
let (is_live, title, category, viewers, started_at) = match data.livestream {
|
||||
Some(live) => {
|
||||
let started_at = live.normalized_started_at();
|
||||
let cat = live
|
||||
.categories
|
||||
.and_then(|cats| cats.into_iter().next())
|
||||
.and_then(|c| c.name)
|
||||
.unwrap_or_default();
|
||||
(
|
||||
true,
|
||||
live.session_title.unwrap_or_default(),
|
||||
cat,
|
||||
live.viewer_count.unwrap_or(0),
|
||||
started_at,
|
||||
)
|
||||
}
|
||||
None => (false, String::new(), String::new(), 0, None),
|
||||
};
|
||||
|
||||
let avatar_url = data.user.and_then(|u| u.profile_pic).unwrap_or_default();
|
||||
|
||||
ChannelCard {
|
||||
channel_name,
|
||||
is_live,
|
||||
title,
|
||||
category,
|
||||
viewers,
|
||||
verified: data.verified,
|
||||
avatar_url,
|
||||
group_name,
|
||||
is_playing: false,
|
||||
chatroom_id: data.chatroom.and_then(|c| c.id),
|
||||
playback_url: data.playback_url,
|
||||
thumbnail_url: None,
|
||||
started_at,
|
||||
}
|
||||
}
|
||||
115
src-tauri/src/services/shortcut.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
use crate::error::AppError;
|
||||
use std::process::Command;
|
||||
|
||||
pub struct ShortcutService;
|
||||
|
||||
impl ShortcutService {
|
||||
/// Repairs Desktop / Start Menu shortcuts that still point at an older
|
||||
/// installation path (e.g. the legacy `…\Programs\LD KickWatch` build).
|
||||
pub fn repair_shortcuts() -> Result<usize, AppError> {
|
||||
let current_exe = std::env::current_exe().map_err(AppError::Io)?;
|
||||
let exe_path_str = current_exe.to_string_lossy().to_string();
|
||||
|
||||
let ps_script = r#"
|
||||
$target = $env:LDKW_SHORTCUT_TARGET
|
||||
if ([string]::IsNullOrWhiteSpace($target)) { Write-Output "FIXED=0"; exit 0 }
|
||||
$dir = [System.IO.Path]::GetDirectoryName($target)
|
||||
$shell = New-Object -ComObject WScript.Shell
|
||||
$paths = @(
|
||||
(Join-Path ([System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::DesktopDirectory)) "LD KickWatch.lnk"),
|
||||
(Join-Path ([System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Programs)) "LD KickWatch.lnk")
|
||||
)
|
||||
$fixed = 0
|
||||
foreach ($p in $paths) {
|
||||
if (Test-Path $p) {
|
||||
$s = $shell.CreateShortcut($p)
|
||||
$changed = $false
|
||||
if ($s.TargetPath -ne $target) { $s.TargetPath = $target; $changed = $true }
|
||||
if ($s.WorkingDirectory -ne $dir) { $s.WorkingDirectory = $dir; $changed = $true }
|
||||
if ($s.IconLocation -ne "$target,0") { $s.IconLocation = "$target,0"; $changed = $true }
|
||||
if ($changed) { $s.Save(); $fixed++ }
|
||||
}
|
||||
}
|
||||
Write-Output "FIXED=$fixed"
|
||||
"#;
|
||||
|
||||
let mut cmd = Command::new("powershell");
|
||||
cmd.args(["-NoProfile", "-NonInteractive", "-Command", ps_script])
|
||||
.env("LDKW_SHORTCUT_TARGET", &exe_path_str);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
let output = cmd.output().map_err(AppError::Io)?;
|
||||
if !output.status.success() {
|
||||
return Err(AppError::General(
|
||||
"Kısayollar onarılamadı".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let fixed = stdout
|
||||
.lines()
|
||||
.find_map(|line| line.trim().strip_prefix("FIXED="))
|
||||
.and_then(|value| value.trim().parse::<usize>().ok())
|
||||
.unwrap_or(0);
|
||||
|
||||
if fixed > 0 {
|
||||
log::info!("{} kısayol güncel kurulum yoluna onarıldı", fixed);
|
||||
}
|
||||
|
||||
Ok(fixed)
|
||||
}
|
||||
|
||||
pub fn create_desktop_shortcut() -> Result<String, AppError> {
|
||||
let current_exe = std::env::current_exe().map_err(AppError::Io)?;
|
||||
let exe_path_str = current_exe.to_string_lossy().to_string();
|
||||
|
||||
let ps_script = r#"
|
||||
$target = $env:LDKW_SHORTCUT_TARGET
|
||||
if ([string]::IsNullOrWhiteSpace($target)) {
|
||||
Write-Error "Hedef dosya yolu bulunamadı"
|
||||
exit 1
|
||||
}
|
||||
$WshShell = New-Object -ComObject WScript.Shell
|
||||
$Desktop = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::DesktopDirectory)
|
||||
$ShortcutPath = [System.IO.Path]::Combine($Desktop, "LD KickWatch.lnk")
|
||||
$Shortcut = $WshShell.CreateShortcut($ShortcutPath)
|
||||
$Shortcut.TargetPath = $target
|
||||
$Shortcut.WorkingDirectory = [System.IO.Path]::GetDirectoryName($target)
|
||||
$Shortcut.Description = "LD KickWatch - Kick.com Canlı Yayın İzleme Stüdyosu"
|
||||
$Shortcut.IconLocation = "$target,0"
|
||||
$Shortcut.Save()
|
||||
Write-Output "OK"
|
||||
"#;
|
||||
|
||||
let mut cmd = Command::new("powershell");
|
||||
cmd.args(["-NoProfile", "-NonInteractive", "-Command", ps_script])
|
||||
.env("LDKW_SHORTCUT_TARGET", &exe_path_str);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
let output = cmd.output().map_err(AppError::Io)?;
|
||||
|
||||
if output.status.success() {
|
||||
log::info!("Masaüstü kısayolu oluşturuldu: {}", exe_path_str);
|
||||
Ok("Masaüstü kısayolu başarıyla oluşturuldu!".to_string())
|
||||
} else {
|
||||
let err = String::from_utf8_lossy(&output.stderr).to_string();
|
||||
log::error!("Masaüstü kısayolu oluşturulamadı: {}", err);
|
||||
Err(AppError::General(format!(
|
||||
"Kısayol oluşturulamadı: {}",
|
||||
err
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
143
src-tauri/src/services/sound.rs
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
use crate::error::AppError;
|
||||
use std::f64::consts::PI;
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Cursor};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct SoundService;
|
||||
|
||||
impl SoundService {
|
||||
pub fn play_notification(custom_path: Option<&str>, is_alert: bool) -> Result<(), AppError> {
|
||||
let custom_file = custom_path
|
||||
.filter(|p| !p.trim().is_empty() && Path::new(p).exists())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let (_stream, stream_handle) = match rodio::OutputStream::try_default() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
log::warn!("Ses çıkış aygıtı açılamadı: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let sink = match rodio::Sink::try_new(&stream_handle) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
log::warn!("Ses kanalı oluşturulamadı: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(path) = custom_file {
|
||||
if let Ok(file) = File::open(path) {
|
||||
let reader = BufReader::new(file);
|
||||
if let Ok(source) = rodio::Decoder::new(reader) {
|
||||
sink.append(source);
|
||||
sink.sleep_until_end();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: synthesized pleasant harmonic chime
|
||||
let wav_bytes = if is_alert {
|
||||
Self::generate_chime_wav(659.25, 1046.50, 300)
|
||||
} else {
|
||||
Self::generate_chime_wav(587.33, 880.0, 260)
|
||||
};
|
||||
|
||||
let cursor = Cursor::new(wav_bytes);
|
||||
if let Ok(source) = rodio::Decoder::new(cursor) {
|
||||
sink.append(source);
|
||||
sink.sleep_until_end();
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn generate_chime_wav(freq1: f64, freq2: f64, duration_ms: u32) -> Vec<u8> {
|
||||
let sample_rate: u32 = 44100;
|
||||
let total_samples = (sample_rate * duration_ms) / 1000;
|
||||
let half_samples = total_samples / 2;
|
||||
|
||||
let mut pcm_samples: Vec<i16> = Vec::with_capacity(total_samples as usize);
|
||||
|
||||
for i in 0..total_samples {
|
||||
let freq = if i < half_samples { freq1 } else { freq2 };
|
||||
let local_index = if i < half_samples {
|
||||
i
|
||||
} else {
|
||||
i - half_samples
|
||||
};
|
||||
let local_len = if i < half_samples {
|
||||
half_samples
|
||||
} else {
|
||||
total_samples - half_samples
|
||||
};
|
||||
|
||||
let t = local_index as f64 / sample_rate as f64;
|
||||
let mut envelope = (-4.5 * (local_index as f64 / local_len as f64)).exp();
|
||||
if local_index < 200 {
|
||||
envelope *= local_index as f64 / 200.0;
|
||||
}
|
||||
|
||||
let sample_f = (2.0 * PI * freq * t).sin() * 0.35 * envelope;
|
||||
let sample_i16 = (sample_f * i16::MAX as f64) as i16;
|
||||
pcm_samples.push(sample_i16);
|
||||
}
|
||||
|
||||
let mut wav = Vec::with_capacity(44 + pcm_samples.len() * 2);
|
||||
let data_size = (pcm_samples.len() * 2) as u32;
|
||||
|
||||
// RIFF header
|
||||
wav.extend_from_slice(b"RIFF");
|
||||
wav.extend_from_slice(&(36 + data_size).to_le_bytes());
|
||||
wav.extend_from_slice(b"WAVE");
|
||||
|
||||
// fmt chunk
|
||||
wav.extend_from_slice(b"fmt ");
|
||||
wav.extend_from_slice(&16u32.to_le_bytes()); // Subchunk1Size
|
||||
wav.extend_from_slice(&1u16.to_le_bytes()); // AudioFormat (1 = PCM)
|
||||
wav.extend_from_slice(&1u16.to_le_bytes()); // NumChannels (1 = Mono)
|
||||
wav.extend_from_slice(&sample_rate.to_le_bytes());
|
||||
wav.extend_from_slice(&(sample_rate * 2).to_le_bytes()); // ByteRate
|
||||
wav.extend_from_slice(&2u16.to_le_bytes()); // BlockAlign
|
||||
wav.extend_from_slice(&16u16.to_le_bytes()); // BitsPerSample
|
||||
|
||||
// data chunk
|
||||
wav.extend_from_slice(b"data");
|
||||
wav.extend_from_slice(&data_size.to_le_bytes());
|
||||
for s in pcm_samples {
|
||||
wav.extend_from_slice(&s.to_le_bytes());
|
||||
}
|
||||
|
||||
wav
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_generate_chime_wav_valid_riff_header() {
|
||||
let wav = SoundService::generate_chime_wav(587.33, 880.0, 260);
|
||||
assert!(wav.len() > 44);
|
||||
assert_eq!(&wav[0..4], b"RIFF");
|
||||
assert_eq!(&wav[8..12], b"WAVE");
|
||||
assert_eq!(&wav[12..16], b"fmt ");
|
||||
assert_eq!(&wav[36..40], b"data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_alert_chime_wav_duration() {
|
||||
let wav = SoundService::generate_chime_wav(659.25, 1046.50, 300);
|
||||
assert!(wav.len() > 44);
|
||||
let sample_rate = 44100u32;
|
||||
let expected_samples = (sample_rate * 300) / 1000;
|
||||
let expected_data_bytes = expected_samples * 2;
|
||||
assert_eq!((wav.len() - 44) as u32, expected_data_bytes);
|
||||
}
|
||||
}
|
||||
49
src-tauri/src/state.rs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
use crate::error::AppError;
|
||||
use crate::models::AppConfig;
|
||||
use crate::services::{
|
||||
ConfigService, KickApiService, PlayerService, PollingService, PusherChatService,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use tauri::AppHandle;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
pub struct AppState {
|
||||
pub app_handle: AppHandle,
|
||||
pub config: Arc<RwLock<AppConfig>>,
|
||||
pub config_service: Arc<ConfigService>,
|
||||
pub api: Arc<KickApiService>,
|
||||
pub player: Arc<PlayerService>,
|
||||
pub polling: Arc<PollingService>,
|
||||
pub chat: Arc<PusherChatService>,
|
||||
pub active_stream: Arc<RwLock<Option<String>>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(app_handle: AppHandle) -> Result<Self, AppError> {
|
||||
let config_service = Arc::new(ConfigService::new()?);
|
||||
let initial_config = config_service.load();
|
||||
let config = Arc::new(RwLock::new(initial_config));
|
||||
|
||||
let api = Arc::new(KickApiService::new()?);
|
||||
let player = Arc::new(PlayerService::new());
|
||||
let polling = Arc::new(PollingService::new(
|
||||
app_handle.clone(),
|
||||
api.clone(),
|
||||
config.clone(),
|
||||
config_service.clone(),
|
||||
));
|
||||
let chat = Arc::new(PusherChatService::new(app_handle.clone()));
|
||||
let active_stream = Arc::new(RwLock::new(None));
|
||||
|
||||
Ok(Self {
|
||||
app_handle,
|
||||
config,
|
||||
config_service,
|
||||
api,
|
||||
player,
|
||||
polling,
|
||||
chat,
|
||||
active_stream,
|
||||
})
|
||||
}
|
||||
}
|
||||
60
src-tauri/tauri.conf.json
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
{
|
||||
"productName": "LD KickWatch",
|
||||
"version": "2.6.12",
|
||||
"identifier": "com.ldkickwatch.desktop",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
"devUrl": "http://localhost:1420",
|
||||
"beforeBuildCommand": "npm run build",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "LD KickWatch",
|
||||
"width": 1340,
|
||||
"height": 820,
|
||||
"minWidth": 820,
|
||||
"minHeight": 560,
|
||||
"resizable": true,
|
||||
"fullscreen": false,
|
||||
"decorations": false,
|
||||
"transparent": true,
|
||||
"center": true,
|
||||
"visible": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self' ipc: http://ipc.localhost; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https: http:; media-src 'self' data: blob: https: http:; frame-src 'self' https://player.kick.com https://kick.com; connect-src 'self' ipc: http://ipc.localhost https: http: wss:;"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"resources": {
|
||||
"resources": ""
|
||||
},
|
||||
"windows": {
|
||||
"nsis": {
|
||||
"installerHooks": "installer-hooks.nsh"
|
||||
}
|
||||
},
|
||||
"createUpdaterArtifacts": true,
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.png",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IERGNkY3ODA1MjU1QTZDMDgKUldRSWJGb2xCWGh2My9kVlo1S1Zsd0EvVVVpcEhSVVZPZGpBQkpZTzB5Z0R2RDB2Y2JKRFRaMU0K",
|
||||
"endpoints": [
|
||||
"https://ttmadethat.shop/updates/ld-kickwatch/latest.json"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
242
src/App.tsx
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
import React, { useEffect, useState } from 'react';
|
||||
import { Titlebar } from './components/Titlebar';
|
||||
import { Sidebar } from './components/Sidebar';
|
||||
import { LiveChannelsDrawer } from './components/LiveChannelsDrawer';
|
||||
import { ChannelList } from './components/ChannelList';
|
||||
import { PlayerView } from './components/PlayerView';
|
||||
import { SquadView } from './components/SquadView';
|
||||
import { SettingsView } from './components/SettingsView';
|
||||
import { AboutView } from './components/AboutView';
|
||||
import { ChatDrawer } from './components/ChatDrawer';
|
||||
import { ToastContainer } from './components/ToastContainer';
|
||||
import { UpdateModal } from './components/UpdateModal';
|
||||
import { UpdateBanner } from './components/UpdateBanner';
|
||||
import { useAppStore } from './store/appStore';
|
||||
import { tauriApi } from './lib/tauri';
|
||||
|
||||
export const App: React.FC = () => {
|
||||
const activeTab = useAppStore((s) => s.activeTab);
|
||||
const loadConfig = useAppStore((s) => s.loadConfig);
|
||||
const loadChannels = useAppStore((s) => s.loadChannels);
|
||||
const loadTopTrChannels = useAppStore((s) => s.loadTopTrChannels);
|
||||
const loadSmallTrChannels = useAppStore((s) => s.loadSmallTrChannels);
|
||||
const refreshChannels = useAppStore((s) => s.refreshChannels);
|
||||
const addChatMessage = useAppStore((s) => s.addChatMessage);
|
||||
const toggleChatDrawer = useAppStore((s) => s.toggleChatDrawer);
|
||||
const checkForUpdates = useAppStore((s) => s.checkForUpdates);
|
||||
const loadKickProfile = useAppStore((s) => s.loadKickProfile);
|
||||
const setKickProfile = useAppStore((s) => s.setKickProfile);
|
||||
const isFullscreen = useAppStore((s) => s.isFullscreen);
|
||||
const setFullscreen = useAppStore((s) => s.setFullscreen);
|
||||
const isPlaying = useAppStore((s) => s.isPlaying);
|
||||
const activeChannel = useAppStore((s) => s.activeChannel);
|
||||
const activeStream = useAppStore((s) => s.activeStream);
|
||||
const squadSlots = useAppStore((s) => s.squadSlots);
|
||||
const [miniCorner, setMiniCorner] = useState<'right' | 'left'>('right');
|
||||
|
||||
useEffect(() => {
|
||||
// Initial data loading
|
||||
loadConfig();
|
||||
loadChannels();
|
||||
loadTopTrChannels();
|
||||
loadSmallTrChannels();
|
||||
loadKickProfile();
|
||||
|
||||
// Silent background startup update check (non-blocking, fails gracefully if offline)
|
||||
const updateTimer = setTimeout(() => {
|
||||
checkForUpdates(false);
|
||||
}, 1200);
|
||||
|
||||
// Tauri backend event listeners with leak-safe mounting guard
|
||||
let mounted = true;
|
||||
const unlistens: Array<() => void> = [];
|
||||
|
||||
const registerListener = async (promise: Promise<() => void>) => {
|
||||
try {
|
||||
const unlisten = await promise;
|
||||
if (mounted) {
|
||||
unlistens.push(unlisten);
|
||||
} else {
|
||||
unlisten();
|
||||
}
|
||||
} catch {
|
||||
// Listener initialization caught cleanly
|
||||
}
|
||||
};
|
||||
|
||||
registerListener(
|
||||
tauriApi.onChannelsLiveReady((liveChannels) => {
|
||||
useAppStore.setState({ channels: liveChannels, isLoadingChannels: false });
|
||||
})
|
||||
);
|
||||
|
||||
registerListener(
|
||||
tauriApi.onChannelsUpdated((updatedChannels) => {
|
||||
useAppStore.setState({ channels: updatedChannels, isLoadingChannels: false });
|
||||
})
|
||||
);
|
||||
|
||||
registerListener(
|
||||
tauriApi.onChatMessage((msg) => {
|
||||
addChatMessage(msg);
|
||||
})
|
||||
);
|
||||
|
||||
registerListener(
|
||||
tauriApi.onChatConnectionState((connected) => {
|
||||
useAppStore.setState({ isChatConnected: connected });
|
||||
})
|
||||
);
|
||||
|
||||
registerListener(
|
||||
tauriApi.onStreamPlaybackChanged((info) => {
|
||||
const current = useAppStore.getState().activeChannel;
|
||||
if (current && current.channel_name.toLowerCase() !== info.channel_name.toLowerCase()) {
|
||||
return;
|
||||
}
|
||||
useAppStore.setState({
|
||||
activeStream: info,
|
||||
isPlaying: true,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
registerListener(
|
||||
tauriApi.onStreamStopped(() => {
|
||||
void useAppStore.getState().disconnectChat();
|
||||
useAppStore.setState({
|
||||
isPlaying: false,
|
||||
activeStream: null,
|
||||
activeChannel: null,
|
||||
isChatDrawerOpen: false,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
registerListener(
|
||||
tauriApi.onKickAuthChanged((profile) => {
|
||||
setKickProfile(profile);
|
||||
})
|
||||
);
|
||||
|
||||
registerListener(
|
||||
tauriApi.onKickFollowChanged(({ channel_slug, following }) => {
|
||||
void tauriApi
|
||||
.getChannels()
|
||||
.then((cards) => {
|
||||
useAppStore.setState({ channels: cards });
|
||||
})
|
||||
.catch(() => {});
|
||||
useAppStore.getState().addToast({
|
||||
type: 'success',
|
||||
title: following ? 'Takip Edildi' : 'Takipten Çıkıldı',
|
||||
message: `${channel_slug} ${
|
||||
following ? 'Kick hesabında takip listene eklendi.' : 'takip listenden çıkarıldı.'
|
||||
}`,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
registerListener(
|
||||
tauriApi.onNotificationsChanged((enabled) => {
|
||||
useAppStore.getState().applyNotificationsEnabled(enabled);
|
||||
})
|
||||
);
|
||||
|
||||
// Keyboard Shortcuts
|
||||
const handleKeyDown = async (e: KeyboardEvent) => {
|
||||
if (e.key === 'F5') {
|
||||
e.preventDefault();
|
||||
refreshChannels();
|
||||
} else if (e.key === 'Escape') {
|
||||
// Esc exits app fullscreen first, then falls back to closing chat
|
||||
if (useAppStore.getState().isFullscreen) {
|
||||
await setFullscreen(false);
|
||||
return;
|
||||
}
|
||||
toggleChatDrawer(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
clearTimeout(updateTimer);
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
unlistens.forEach((u) => u());
|
||||
};
|
||||
}, []);
|
||||
|
||||
const isVideoSurfaceRoute =
|
||||
(activeTab === 'player' && isPlaying && activeStream?.player_mode !== 'external') ||
|
||||
(activeTab === 'squad' && squadSlots.some(Boolean));
|
||||
|
||||
const isMiniPlayer =
|
||||
!isFullscreen &&
|
||||
isPlaying &&
|
||||
Boolean(activeChannel) &&
|
||||
activeTab !== 'player' &&
|
||||
activeTab !== 'squad' &&
|
||||
activeStream?.player_mode !== 'external';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`h-screen w-screen flex flex-col overflow-hidden text-slate-100 select-none ${
|
||||
isVideoSurfaceRoute ? 'bg-transparent' : 'bg-[#101318]'
|
||||
}`}
|
||||
>
|
||||
{/* Native-feel custom Titlebar (hidden in fullscreen) */}
|
||||
{!isFullscreen && <Titlebar />}
|
||||
|
||||
{/* Non-intrusive Update Notification Banner */}
|
||||
{!isFullscreen && <UpdateBanner />}
|
||||
|
||||
{/* Main Workspace */}
|
||||
<div className="flex-1 flex overflow-hidden">
|
||||
{/* Navigation Rail (hidden in fullscreen) */}
|
||||
{!isFullscreen && <Sidebar />}
|
||||
|
||||
{/* Expandable Active Live Followed Channels Drawer (side-by-side without stopping video) */}
|
||||
{!isFullscreen && <LiveChannelsDrawer />}
|
||||
|
||||
{/* View Switcher */}
|
||||
<main className="flex-1 flex overflow-hidden relative">
|
||||
{activeTab === 'channels' && <ChannelList />}
|
||||
{(activeTab === 'player' || (isPlaying && Boolean(activeChannel))) && (
|
||||
<div
|
||||
className={
|
||||
activeTab === 'player'
|
||||
? 'flex-1 flex overflow-hidden'
|
||||
: isMiniPlayer
|
||||
? `absolute bottom-4 ${
|
||||
miniCorner === 'right' ? 'right-4' : 'left-4'
|
||||
} z-40 w-[340px] sm:w-[360px] rounded-2xl bg-[#151921] border-2 border-[#60E0B1]/70 shadow-[0_16px_48px_rgba(0,0,0,0.85)] overflow-hidden flex flex-col`
|
||||
: 'hidden'
|
||||
}
|
||||
>
|
||||
<PlayerView
|
||||
isMiniPlayer={isMiniPlayer}
|
||||
miniCorner={miniCorner}
|
||||
onToggleMiniCorner={() =>
|
||||
setMiniCorner((prev) => (prev === 'right' ? 'left' : 'right'))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'squad' && <SquadView />}
|
||||
{activeTab === 'settings' && <SettingsView />}
|
||||
{activeTab === 'about' && <AboutView />}
|
||||
</main>
|
||||
|
||||
{/* Stream-scoped Live Pusher Chat Drawer (only mounted with active PlayerView) */}
|
||||
{activeTab === 'player' && isPlaying && activeChannel && <ChatDrawer />}
|
||||
</div>
|
||||
|
||||
{/* Global Notifications & Modals */}
|
||||
<ToastContainer />
|
||||
<UpdateModal />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export default App;
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
<Application x:Class="KickStreamHub.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:conv="clr-namespace:KickStreamHub.Converters">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<BooleanToVisibilityConverter x:Key="BoolToVis" />
|
||||
<conv:BoolToVisibilityInverseConverter x:Key="InverseBoolToVis" />
|
||||
<conv:LiveToBrushConverter x:Key="LiveToBrush" />
|
||||
<conv:LiveTextConverter x:Key="LiveTextConverter" />
|
||||
<conv:ChatConnectionTextConverter x:Key="ChatConnTextConverter" />
|
||||
<conv:PauseTextConverter x:Key="PauseTextConverter" />
|
||||
<conv:ViewerFormatConverter x:Key="ViewerFormat" />
|
||||
<conv:StringToBrushConverter x:Key="StringToBrush" />
|
||||
<conv:PageVisibilityConverter x:Key="PageVisConverter" />
|
||||
<conv:ActivePageMatchConverter x:Key="ActivePageMatch" />
|
||||
<conv:NonEmptyToVisibilityConverter x:Key="NonEmptyToVis" />
|
||||
<conv:NullToVisibilityConverter x:Key="NullToVis" />
|
||||
<conv:PlayButtonTextConverter x:Key="PlayButtonTextConverter" />
|
||||
<conv:TheaterButtonTextConverter x:Key="TheaterButtonTextConverter" />
|
||||
<conv:FullScreenButtonTextConverter x:Key="FullScreenButtonTextConverter" />
|
||||
<conv:MuteButtonTextConverter x:Key="MuteButtonTextConverter" />
|
||||
<conv:MultiLayoutTextConverter x:Key="MultiLayoutTextConverter" />
|
||||
<conv:SoloAudioTextConverter x:Key="SoloAudioTextConverter" />
|
||||
<conv:InitialsConverter x:Key="InitialsConverter" />
|
||||
<conv:AvatarImageConverter x:Key="AvatarImageConverter" />
|
||||
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="Resources/Styles.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
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 açık pencereyi öne getir ve ikinci örneği derhal sonlandır
|
||||
try
|
||||
{
|
||||
using var evt = EventWaitHandle.OpenExisting(ActivateEventName);
|
||||
evt.Set();
|
||||
}
|
||||
catch { }
|
||||
|
||||
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);
|
||||
|
||||
try
|
||||
{
|
||||
System.Windows.Media.Animation.Timeline.DesiredFrameRateProperty.OverrideMetadata(
|
||||
typeof(System.Windows.Media.Animation.Timeline),
|
||||
new FrameworkPropertyMetadata(60));
|
||||
}
|
||||
catch { }
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,267 +0,0 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using WpfColor = System.Windows.Media.Color;
|
||||
using WpfColors = System.Windows.Media.Colors;
|
||||
using WpfColorConverter = System.Windows.Media.ColorConverter;
|
||||
|
||||
namespace KickStreamHub.Converters;
|
||||
|
||||
public class BoolToVisibilityInverseConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? Visibility.Collapsed : Visibility.Visible;
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class LiveTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? "● CANLI YAYINDA" : "ÇEVRİMDIŞI";
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class ChatConnectionTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? "Bağlı" : "Bağlanıyor...";
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class LiveToBrushConverter : IValueConverter
|
||||
{
|
||||
private static readonly SolidColorBrush LiveBrush = new(WpfColor.FromRgb(0, 231, 1));
|
||||
private static readonly SolidColorBrush OfflineBrush = new(WpfColor.FromRgb(51, 65, 85));
|
||||
static LiveToBrushConverter() { LiveBrush.Freeze(); OfflineBrush.Freeze(); }
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
var isLive = value is true;
|
||||
if (targetType == typeof(WpfColor))
|
||||
return isLive ? WpfColors.LimeGreen : WpfColors.SlateGray;
|
||||
return isLive ? LiveBrush : OfflineBrush;
|
||||
}
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class PauseTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? "▶ Devam" : "⏸ Duraklat";
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class ViewerFormatConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long v)
|
||||
return v >= 1000 ? $"{v / 1000.0:0.0}B" : v.ToString();
|
||||
return "0";
|
||||
}
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class PageVisibilityConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is string current && parameter is string target)
|
||||
return current.Equals(target, StringComparison.OrdinalIgnoreCase)
|
||||
? Visibility.Visible : Visibility.Collapsed;
|
||||
return Visibility.Collapsed;
|
||||
}
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class ActivePageMatchConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is string current && parameter is string target)
|
||||
return current.Equals(target, StringComparison.OrdinalIgnoreCase);
|
||||
return false;
|
||||
}
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class NonEmptyToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
bool hasText = value is string s && !string.IsNullOrWhiteSpace(s);
|
||||
bool invert = parameter is string p && p.Equals("invert", StringComparison.OrdinalIgnoreCase);
|
||||
if (invert) hasText = !hasText;
|
||||
return hasText ? Visibility.Visible : Visibility.Collapsed;
|
||||
}
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class NullToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
bool isNotNull = value is not null;
|
||||
bool invert = parameter is string p && p.Equals("invert", StringComparison.OrdinalIgnoreCase);
|
||||
if (invert) isNotNull = !isNotNull;
|
||||
return isNotNull ? Visibility.Visible : Visibility.Collapsed;
|
||||
}
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class PlayButtonTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? "⏹ YAYINI DURDUR" : "▶ YAYINI İZLE";
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class TheaterButtonTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? "🗗 Normal" : "🗖 Sinema Modu";
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class FullScreenButtonTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? "🗗 Çık (Esc)" : "⛶ Tam Ekran";
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class MuteButtonTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? "🔇 Sesi Aç" : "🔊 Sesi Kapat";
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class MultiLayoutTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? "▯▯ 2'li Yan Yana Mod" : "⊞ 4'lü (2x2) Izgara Mod";
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class SoloAudioTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? "🔇 Bu Ekranı Dinle" : "🔊 Ses Açık";
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class InitialsConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is string s && !string.IsNullOrWhiteSpace(s))
|
||||
{
|
||||
var clean = s.Trim().TrimStart('@');
|
||||
if (clean.Length == 0) return "?";
|
||||
return clean.Length >= 2 ? clean[..2].ToUpperInvariant() : clean[..1].ToUpperInvariant();
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Diskteki avatar dosyasını kilitlemeden (BitmapCacheOption.OnLoad) belleğe yükler.
|
||||
/// Böylece AvatarCacheService dosyayı güncellerken IOException (file lock) oluşmaz.
|
||||
/// </summary>
|
||||
public class AvatarImageConverter : IValueConverter
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, BitmapImage> s_avatarCache = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is not string path || string.IsNullOrWhiteSpace(path))
|
||||
return null;
|
||||
|
||||
if (s_avatarCache.TryGetValue(path, out var cached))
|
||||
return cached;
|
||||
|
||||
if (!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();
|
||||
|
||||
s_avatarCache[path] = bitmap;
|
||||
return bitmap;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public class StringToBrushConverter : IValueConverter
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, SolidColorBrush> BrushCache = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static readonly SolidColorBrush DefaultBrush = CreateFrozenBrush(WpfColor.FromRgb(0, 231, 1));
|
||||
|
||||
private static SolidColorBrush CreateFrozenBrush(WpfColor color)
|
||||
{
|
||||
var brush = new SolidColorBrush(color);
|
||||
brush.Freeze();
|
||||
return brush;
|
||||
}
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is string hex && !string.IsNullOrWhiteSpace(hex))
|
||||
{
|
||||
return BrushCache.GetOrAdd(hex.Trim(), key =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var color = (WpfColor)WpfColorConverter.ConvertFromString(key);
|
||||
return CreateFrozenBrush(color);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return DefaultBrush;
|
||||
}
|
||||
});
|
||||
}
|
||||
return DefaultBrush;
|
||||
}
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
|
@ -1,111 +0,0 @@
|
|||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace KickStreamHub.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Windows Job Object kullanarak alt süreçleri (VLC, Streamlink, MPV) ana uygulamaya bağlar.
|
||||
/// Ana uygulama kapandığında veya çöktüğünde işletim sistemi seviyesinde TÜM alt süreçlerin
|
||||
/// anında sonlandırılmasını garanti eder (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE).
|
||||
/// </summary>
|
||||
public static class ChildProcessTracker
|
||||
{
|
||||
private static readonly IntPtr s_jobHandle;
|
||||
|
||||
static ChildProcessTracker()
|
||||
{
|
||||
try
|
||||
{
|
||||
s_jobHandle = CreateJobObject(IntPtr.Zero, null);
|
||||
if (s_jobHandle == IntPtr.Zero) return;
|
||||
|
||||
var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION
|
||||
{
|
||||
LimitFlags = 0x2000 // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
};
|
||||
var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
||||
{
|
||||
BasicLimitInformation = info
|
||||
};
|
||||
|
||||
int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
|
||||
IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
|
||||
try
|
||||
{
|
||||
Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);
|
||||
SetInformationJobObject(s_jobHandle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(extendedInfoPtr);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Job Object desteklenmeyen ortamlarda sessizce geçilir
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddProcess(Process? process)
|
||||
{
|
||||
if (process is null) return;
|
||||
try
|
||||
{
|
||||
if (s_jobHandle != IntPtr.Zero && !process.HasExited)
|
||||
{
|
||||
AssignProcessToJobObject(s_jobHandle, process.Handle);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string? lpName);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
|
||||
|
||||
private enum JobObjectInfoType
|
||||
{
|
||||
ExtendedLimitInformation = 9
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct JOBOBJECT_BASIC_LIMIT_INFORMATION
|
||||
{
|
||||
public long PerProcessUserTimeLimit;
|
||||
public long PerJobUserTimeLimit;
|
||||
public uint LimitFlags;
|
||||
public UIntPtr MinimumWorkingSetSize;
|
||||
public UIntPtr MaximumWorkingSetSize;
|
||||
public uint ActiveProcessLimit;
|
||||
public UIntPtr Affinity;
|
||||
public uint PriorityClass;
|
||||
public uint SchedulingClass;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct IO_COUNTERS
|
||||
{
|
||||
public ulong ReadOperationCount;
|
||||
public ulong WriteOperationCount;
|
||||
public ulong OtherOperationCount;
|
||||
public ulong ReadTransferCount;
|
||||
public ulong WriteTransferCount;
|
||||
public ulong OtherTransferCount;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
||||
{
|
||||
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
|
||||
public IO_COUNTERS IoInfo;
|
||||
public UIntPtr ProcessMemoryLimit;
|
||||
public UIntPtr JobMemoryLimit;
|
||||
public UIntPtr PeakProcessMemoryLimit;
|
||||
public UIntPtr PeakJobMemoryLimit;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,182 +0,0 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using KickStreamHub.Converters;
|
||||
using KickStreamHub.ViewModels;
|
||||
using WpfColor = System.Windows.Media.Color;
|
||||
using WpfImage = System.Windows.Controls.Image;
|
||||
|
||||
namespace KickStreamHub.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Kick sohbet mesajlarındaki [emote:ID:Name] ifadelerini gerçek görsel (InlineUIContainer + Image)
|
||||
/// olarak ayrıştırır ve bellek içi önbellek (EmoteCache) ile yüksek performanslı şekilde TextBlock'a çizer.
|
||||
/// </summary>
|
||||
public static partial class RichChatHelper
|
||||
{
|
||||
[GeneratedRegex(@"\[emote:(\d+):([^\]]+)\]")]
|
||||
private static partial Regex EmotePattern();
|
||||
|
||||
private static readonly ConcurrentDictionary<string, BitmapImage> EmoteCache = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static readonly ConcurrentDictionary<string, Task<BitmapImage?>> InFlightEmotes = 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 bmp = await InFlightEmotes.GetOrAdd(emoteId, FetchEmoteBitmapAsync).ConfigureAwait(false);
|
||||
if (bmp != null)
|
||||
{
|
||||
await targetImage.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
targetImage.Source = bmp;
|
||||
});
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static async Task<BitmapImage?> FetchEmoteBitmapAsync(string emoteId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var url = $"https://files.kick.com/emotes/{emoteId}/fullsize";
|
||||
var bytes = await EmoteHttp.GetByteArrayAsync(url).ConfigureAwait(false);
|
||||
if (bytes.Length == 0) return null;
|
||||
|
||||
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;
|
||||
return bmp;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseWPF>true</UseWPF>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>KickStreamHub</RootNamespace>
|
||||
<AssemblyName>LDKickWatch</AssemblyName>
|
||||
<Version>1.8.0</Version>
|
||||
<AssemblyVersion>1.8.0.0</AssemblyVersion>
|
||||
<FileVersion>1.8.0.0</FileVersion>
|
||||
<Product>LD KickWatch</Product>
|
||||
<AssemblyTitle>LD KickWatch</AssemblyTitle>
|
||||
<Company>LD KickWatch</Company>
|
||||
<ApplicationIcon>Resources\app.ico</ApplicationIcon>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
|
||||
<Platforms>AnyCPU</Platforms>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Resource Include="Resources\app.ico" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4314.35" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
using System.Collections.ObjectModel;
|
||||
|
||||
namespace KickStreamHub.Models;
|
||||
|
||||
public class AppConfig
|
||||
{
|
||||
public ObservableCollection<string> Favorites { get; set; } = new()
|
||||
{
|
||||
"elwind", "wtcn", "pqueen", "unlostv", "kendinemuzisyen"
|
||||
};
|
||||
|
||||
public Dictionary<string, string> ChannelGroups { get; set; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public string PlayerChoice { get; set; } = "embedded";
|
||||
public int RefreshIntervalSeconds { get; set; } = 90;
|
||||
public bool StartMinimized { get; set; } = false;
|
||||
public bool MinimizeToTray { get; set; } = false;
|
||||
public bool NotificationsEnabled { get; set; } = true;
|
||||
public bool SoundNotificationsEnabled { get; set; } = true;
|
||||
public string CustomSoundPath { get; set; } = string.Empty;
|
||||
public bool NotifyOnCategoryChange { get; set; } = true;
|
||||
public string AlertKeywords { get; set; } = string.Empty;
|
||||
public bool RunOnStartup { get; set; } = false;
|
||||
public bool AutoOpenChat { get; set; } = false;
|
||||
public bool ShowEmbeddedChat { get; set; } = true;
|
||||
|
||||
public double WindowWidth { get; set; } = 1320;
|
||||
public double WindowHeight { get; set; } = 800;
|
||||
public double WindowLeft { get; set; } = -1;
|
||||
public double WindowTop { get; set; } = -1;
|
||||
|
||||
public string StreamlinkPath { get; set; } = string.Empty;
|
||||
public string PlayerPath { get; set; } = string.Empty;
|
||||
public string StreamQuality { get; set; } = "best";
|
||||
public string ExtraStreamlinkArgs { get; set; } = string.Empty;
|
||||
|
||||
public string ActivePage { get; set; } = "home";
|
||||
public int ChatMaxMessages { get; set; } = 500;
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
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;
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace KickStreamHub.Models;
|
||||
|
||||
public class KickChannelResponse
|
||||
{
|
||||
[JsonPropertyName("id")]
|
||||
public long Id { get; set; }
|
||||
|
||||
[JsonPropertyName("slug")]
|
||||
public string? Slug { get; set; }
|
||||
|
||||
[JsonPropertyName("verified")]
|
||||
public bool Verified { get; set; }
|
||||
|
||||
[JsonPropertyName("playback_url")]
|
||||
public string? PlaybackUrl { get; set; }
|
||||
|
||||
[JsonPropertyName("user")]
|
||||
public KickUser? User { get; set; }
|
||||
|
||||
[JsonPropertyName("livestream")]
|
||||
public KickLivestream? Livestream { get; set; }
|
||||
|
||||
[JsonPropertyName("chatroom")]
|
||||
public KickChatroom? Chatroom { get; set; }
|
||||
}
|
||||
|
||||
public class KickUser
|
||||
{
|
||||
[JsonPropertyName("username")]
|
||||
public string? Username { get; set; }
|
||||
|
||||
[JsonPropertyName("profile_pic")]
|
||||
public string? ProfilePic { get; set; }
|
||||
}
|
||||
|
||||
public class KickLivestream
|
||||
{
|
||||
[JsonPropertyName("session_title")]
|
||||
public string? SessionTitle { get; set; }
|
||||
|
||||
[JsonPropertyName("viewer_count")]
|
||||
public long ViewerCount { get; set; }
|
||||
|
||||
[JsonPropertyName("categories")]
|
||||
public List<KickCategory>? Categories { get; set; }
|
||||
}
|
||||
|
||||
public class KickCategory
|
||||
{
|
||||
[JsonPropertyName("name")]
|
||||
public string? Name { get; set; }
|
||||
}
|
||||
|
||||
public class KickChatroom
|
||||
{
|
||||
[JsonPropertyName("id")]
|
||||
public long Id { get; set; }
|
||||
}
|
||||
|
|
@ -1,384 +0,0 @@
|
|||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||
|
||||
<!-- Color Palette -->
|
||||
<SolidColorBrush x:Key="BgBrush" Color="#060A10" />
|
||||
<SolidColorBrush x:Key="PanelBrush" Color="#0B111A" />
|
||||
<SolidColorBrush x:Key="CardBrush" Color="#111926" />
|
||||
<SolidColorBrush x:Key="CardHoverBrush" Color="#172234" />
|
||||
<SolidColorBrush x:Key="BorderBrush" Color="#1E2B3E" />
|
||||
<SolidColorBrush x:Key="TextBrush" Color="#F1F5F9" />
|
||||
<SolidColorBrush x:Key="SubtleTextBrush" Color="#94A3B8" />
|
||||
<SolidColorBrush x:Key="MutedTextBrush" Color="#64748B" />
|
||||
<SolidColorBrush x:Key="AccentBrush" Color="#53FC18" />
|
||||
<SolidColorBrush x:Key="AccentDarkBrush" Color="#00C801" />
|
||||
<SolidColorBrush x:Key="DangerBrush" Color="#EF4444" />
|
||||
|
||||
<!-- Default Window Style -->
|
||||
<Style TargetType="Window">
|
||||
<Setter Property="Background" Value="{StaticResource BgBrush}" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
<Setter Property="FontFamily" Value="Segoe UI" />
|
||||
<Setter Property="UseLayoutRounding" Value="True" />
|
||||
<Setter Property="TextOptions.TextFormattingMode" Value="Ideal" />
|
||||
</Style>
|
||||
|
||||
<!-- Primary Accent Button -->
|
||||
<Style TargetType="Button" x:Key="PrimaryButton">
|
||||
<Setter Property="Background" Value="{StaticResource AccentBrush}" />
|
||||
<Setter Property="Foreground" Value="#041208" />
|
||||
<Setter Property="FontWeight" Value="Bold" />
|
||||
<Setter Property="Padding" Value="12,7" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="border" Background="{TemplateBinding Background}" CornerRadius="8" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#6DFF3B" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#3CD00B" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter TargetName="border" Property="Opacity" Value="0.45" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Secondary Dark Button -->
|
||||
<Style TargetType="Button" x:Key="SecondaryButton">
|
||||
<Setter Property="Background" Value="#141E2E" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Padding" Value="11,7" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="8" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#1E2C42" />
|
||||
<Setter TargetName="border" Property="BorderBrush" Value="#314666" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#0E1520" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter TargetName="border" Property="Opacity" Value="0.45" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Subtle Danger Button (for delete/close) -->
|
||||
<Style TargetType="Button" x:Key="DangerButton">
|
||||
<Setter Property="Background" Value="#181824" />
|
||||
<Setter Property="Foreground" Value="#94A3B8" />
|
||||
<Setter Property="Padding" Value="8,5" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="BorderBrush" Value="#252A3A" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="7" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#35161E" />
|
||||
<Setter TargetName="border" Property="BorderBrush" Value="#EF4444" />
|
||||
<Setter Property="Foreground" Value="#FCA5A5" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#4C1519" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Filter Toggle Button (All / Live Only) -->
|
||||
<Style TargetType="ToggleButton" x:Key="FilterChipToggle">
|
||||
<Setter Property="Background" Value="#101824" />
|
||||
<Setter Property="Foreground" Value="#94A3B8" />
|
||||
<Setter Property="BorderBrush" Value="#1E2B3E" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="Padding" Value="10,5" />
|
||||
<Setter Property="FontSize" Value="11" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ToggleButton">
|
||||
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="7" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#192538" />
|
||||
<Setter Property="Foreground" Value="#E2E8F0" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#132D19" />
|
||||
<Setter TargetName="border" Property="BorderBrush" Value="#53FC18" />
|
||||
<Setter Property="Foreground" Value="#53FC18" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Modern TextBox with Tag Placeholder Watermark -->
|
||||
<Style TargetType="TextBox">
|
||||
<Setter Property="Background" Value="#0D141F" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="Padding" Value="10,7" />
|
||||
<Setter Property="FontSize" Value="12.5" />
|
||||
<Setter Property="CaretBrush" Value="{StaticResource AccentBrush}" />
|
||||
<Setter Property="SelectionBrush" Value="#2D6A1E" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="TextBox">
|
||||
<Border x:Name="border"
|
||||
Background="{TemplateBinding Background}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
CornerRadius="8">
|
||||
<Grid>
|
||||
<ScrollViewer x:Name="PART_ContentHost"
|
||||
Margin="{TemplateBinding Padding}"
|
||||
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
|
||||
Focusable="False"
|
||||
HorizontalScrollBarVisibility="Hidden"
|
||||
VerticalScrollBarVisibility="Hidden" />
|
||||
<TextBlock x:Name="Placeholder"
|
||||
Text="{TemplateBinding Tag}"
|
||||
Foreground="#56677D"
|
||||
Margin="{TemplateBinding Padding}"
|
||||
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
|
||||
IsHitTestVisible="False"
|
||||
Visibility="Collapsed" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="Text" Value="">
|
||||
<Setter TargetName="Placeholder" Property="Visibility" Value="Visible" />
|
||||
</Trigger>
|
||||
<Trigger Property="Text" Value="{x:Null}">
|
||||
<Setter TargetName="Placeholder" Property="Visibility" Value="Visible" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="border" Property="BorderBrush" Value="#2D415E" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsKeyboardFocused" Value="True">
|
||||
<Setter TargetName="border" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
|
||||
<Setter TargetName="border" Property="Background" Value="#101927" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Modern Dark ComboBoxItem -->
|
||||
<Style TargetType="ComboBoxItem">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
<Setter Property="Padding" Value="10,8" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBoxItem">
|
||||
<Border x:Name="bd" Background="{TemplateBinding Background}" CornerRadius="6" Margin="3,1" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsHighlighted" Value="True">
|
||||
<Setter TargetName="bd" Property="Background" Value="#1D2B40" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="bd" Property="Background" Value="#16331D" />
|
||||
<Setter Property="Foreground" Value="{StaticResource AccentBrush}" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Modern Dark ComboBox -->
|
||||
<Style TargetType="ComboBox">
|
||||
<Setter Property="Background" Value="#0D141F" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="Padding" Value="10,7" />
|
||||
<Setter Property="FontSize" Value="12.5" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBox">
|
||||
<Grid>
|
||||
<ToggleButton x:Name="ToggleButton"
|
||||
Focusable="False"
|
||||
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
|
||||
ClickMode="Press">
|
||||
<ToggleButton.Template>
|
||||
<ControlTemplate TargetType="ToggleButton">
|
||||
<Border x:Name="border"
|
||||
Background="#0D141F"
|
||||
BorderBrush="{StaticResource BorderBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="8">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="32" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Path Grid.Column="1"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center"
|
||||
Data="M 0 0 L 5 5 L 10 0"
|
||||
Stroke="#94A3B8"
|
||||
StrokeThickness="1.6" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="border" Property="BorderBrush" Value="#2D415E" />
|
||||
<Setter TargetName="border" Property="Background" Value="#121C2B" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="border" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</ToggleButton.Template>
|
||||
</ToggleButton>
|
||||
<ContentPresenter x:Name="ContentSite"
|
||||
IsHitTestVisible="False"
|
||||
Content="{TemplateBinding SelectionBoxItem}"
|
||||
ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
|
||||
ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
|
||||
Margin="12,7,32,7"
|
||||
VerticalAlignment="Center"
|
||||
HorizontalAlignment="Left" />
|
||||
<Popup x:Name="Popup"
|
||||
Placement="Bottom"
|
||||
IsOpen="{TemplateBinding IsDropDownOpen}"
|
||||
AllowsTransparency="True"
|
||||
Focusable="False"
|
||||
PopupAnimation="Fade">
|
||||
<Grid x:Name="DropDown"
|
||||
SnapsToDevicePixels="True"
|
||||
MinWidth="{TemplateBinding ActualWidth}"
|
||||
MaxHeight="{TemplateBinding MaxDropDownHeight}"
|
||||
Margin="0,4,0,0">
|
||||
<Border x:Name="DropDownBorder"
|
||||
Background="#111A28"
|
||||
BorderBrush="#293B54"
|
||||
BorderThickness="1"
|
||||
CornerRadius="8"
|
||||
Padding="2,4">
|
||||
<ScrollViewer SnapsToDevicePixels="True">
|
||||
<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Popup>
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Modern CheckBox -->
|
||||
<Style TargetType="CheckBox">
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="CheckBox">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" Background="Transparent">
|
||||
<Border x:Name="checkBoxBorder"
|
||||
Width="19" Height="19"
|
||||
CornerRadius="5"
|
||||
Background="#0D141F"
|
||||
BorderBrush="#2A3B52"
|
||||
BorderThickness="1.5"
|
||||
VerticalAlignment="Center">
|
||||
<Path x:Name="checkMark"
|
||||
Data="M 3.5 9.5 L 7.5 13.5 L 15.5 5"
|
||||
Stroke="#041208"
|
||||
StrokeThickness="2.2"
|
||||
Visibility="Collapsed" />
|
||||
</Border>
|
||||
<ContentPresenter Margin="9,0,0,0" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="checkBoxBorder" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="checkBoxBorder" Property="Background" Value="{StaticResource AccentBrush}" />
|
||||
<Setter TargetName="checkBoxBorder" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
|
||||
<Setter TargetName="checkMark" Property="Visibility" Value="Visible" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Modern Thin ScrollBar -->
|
||||
<Style TargetType="ScrollBar">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="Width" Value="6" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ScrollBar">
|
||||
<Grid Background="Transparent" Width="{TemplateBinding Width}">
|
||||
<Track x:Name="PART_Track" IsDirectionReversed="True">
|
||||
<Track.Thumb>
|
||||
<Thumb>
|
||||
<Thumb.Template>
|
||||
<ControlTemplate TargetType="Thumb">
|
||||
<Border Background="#26364D" CornerRadius="3" />
|
||||
</ControlTemplate>
|
||||
</Thumb.Template>
|
||||
</Thumb>
|
||||
</Track.Thumb>
|
||||
</Track>
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
</ResourceDictionary>
|
||||
|
Before Width: | Height: | Size: 15 KiB |
|
|
@ -1,81 +0,0 @@
|
|||
using System.IO;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Kanal avatarlarını diskte önbelleğe alır (TTL: 24 saat) ve gerektiğinde
|
||||
/// KickApiService üzerinden indirir. Tüm dosya G/Ç işlemleri iş parçacığı
|
||||
/// güvenlidir; her indirme kendi dosya adını kullandığından çakışma olmaz.
|
||||
/// </summary>
|
||||
public sealed class AvatarCacheService
|
||||
{
|
||||
private static readonly TimeSpan Ttl = TimeSpan.FromHours(24);
|
||||
|
||||
private readonly string _cacheDir;
|
||||
private readonly KickApiService _api;
|
||||
|
||||
public AvatarCacheService(string cacheDir, KickApiService api)
|
||||
{
|
||||
_cacheDir = cacheDir;
|
||||
_api = api;
|
||||
}
|
||||
|
||||
public string GetCachePath(string channelName) => Path.Combine(_cacheDir, $"{Sanitize(channelName)}.png");
|
||||
|
||||
private static string Sanitize(string name)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars())
|
||||
name = name.Replace(c, '_');
|
||||
return name;
|
||||
}
|
||||
|
||||
public bool TryGetFreshCachedPath(string channelName, out string path)
|
||||
{
|
||||
path = GetCachePath(channelName);
|
||||
if (!File.Exists(path)) return false;
|
||||
var age = DateTime.UtcNow - File.GetLastWriteTimeUtc(path);
|
||||
return age < Ttl;
|
||||
}
|
||||
|
||||
public async Task<string?> DownloadAndCacheAsync(string channelName, string url, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
var bytes = await _api.GetImageBytesAsync(url, ct).ConfigureAwait(false);
|
||||
if (bytes is null || bytes.Length == 0) return null;
|
||||
|
||||
var path = GetCachePath(channelName);
|
||||
try
|
||||
{
|
||||
var tmp = path + ".tmp";
|
||||
await File.WriteAllBytesAsync(tmp, bytes, ct).ConfigureAwait(false);
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
return path;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Avatar önbelleğe yazılamadı ({channelName}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void CleanupStale(IEnumerable<string> activeChannels)
|
||||
{
|
||||
try
|
||||
{
|
||||
var activeSet = new HashSet<string>(activeChannels.Select(Sanitize), StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var file in Directory.EnumerateFiles(_cacheDir, "*.png"))
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(file);
|
||||
var age = DateTime.UtcNow - File.GetLastWriteTimeUtc(file);
|
||||
if (!activeSet.Contains(name) && age > TimeSpan.FromDays(7))
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Avatar önbellek temizliği başarısız: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using KickStreamHub.Models;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Uygulama yapılandırmasını %LOCALAPPDATA%\LDKickWatch\config.json
|
||||
/// dosyasında saklar. Eski KickStreamHub klasöründe yapılandırma varsa ilk
|
||||
/// açılışta otomatik olarak taşır.
|
||||
/// </summary>
|
||||
public sealed class ConfigService
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
};
|
||||
|
||||
public string AppDataDirectory { get; }
|
||||
public string ConfigFilePath { get; }
|
||||
public string AvatarCacheDirectory { get; }
|
||||
|
||||
public ConfigService()
|
||||
{
|
||||
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
AppDataDirectory = Path.Combine(localAppData, "LDKickWatch");
|
||||
Directory.CreateDirectory(AppDataDirectory);
|
||||
|
||||
AvatarCacheDirectory = Path.Combine(AppDataDirectory, "avatars");
|
||||
Directory.CreateDirectory(AvatarCacheDirectory);
|
||||
|
||||
ConfigFilePath = Path.Combine(AppDataDirectory, "config.json");
|
||||
|
||||
// Eski klasörden (KickStreamHub) ayarları otomatik taşı
|
||||
if (!File.Exists(ConfigFilePath))
|
||||
{
|
||||
var legacyConfig = Path.Combine(localAppData, "KickStreamHub", "config.json");
|
||||
if (File.Exists(legacyConfig))
|
||||
{
|
||||
try { File.Copy(legacyConfig, ConfigFilePath, overwrite: false); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public AppConfig Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(ConfigFilePath))
|
||||
return new AppConfig();
|
||||
|
||||
var json = File.ReadAllText(ConfigFilePath);
|
||||
var config = JsonSerializer.Deserialize<AppConfig>(json);
|
||||
return config ?? new AppConfig();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Error("Yapılandırma okunamadı, varsayılana dönülüyor.", ex);
|
||||
return new AppConfig();
|
||||
}
|
||||
}
|
||||
|
||||
public void Save(AppConfig config)
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = JsonSerializer.Serialize(config, JsonOptions);
|
||||
File.WriteAllText(ConfigFilePath, json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Error("Yapılandırma kaydedilemedi.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using KickStreamHub.Models;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Kick.com genel API'siyle konuşan servis. .NET'in HttpClient'ı, Python
|
||||
/// tarafında yaşanan curl_cffi kütüphanesinin aksine, birden fazla iş
|
||||
/// parçacığından EŞZAMANLI olarak güvenle kullanılabilir.
|
||||
/// </summary>
|
||||
public sealed class KickApiService
|
||||
{
|
||||
private const string ApiBaseV2 = "https://kick.com/api/v2/channels";
|
||||
private const string ApiBaseV1 = "https://kick.com/api/v1/channels";
|
||||
|
||||
private static readonly HttpClient Http = CreateClient();
|
||||
|
||||
private static HttpClient CreateClient()
|
||||
{
|
||||
var handler = new SocketsHttpHandler
|
||||
{
|
||||
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
|
||||
AutomaticDecompression = System.Net.DecompressionMethods.All,
|
||||
UseProxy = false,
|
||||
};
|
||||
var client = new HttpClient(handler)
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(12),
|
||||
};
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd(
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36");
|
||||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.9");
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<KickChannelResponse?> GetChannelAsync(string channelName, CancellationToken ct = default)
|
||||
{
|
||||
foreach (var baseUrl in new[] { ApiBaseV2, ApiBaseV1 })
|
||||
{
|
||||
try
|
||||
{
|
||||
using var resp = await Http.GetAsync($"{baseUrl}/{channelName}", ct).ConfigureAwait(false);
|
||||
if (!resp.IsSuccessStatusCode)
|
||||
continue;
|
||||
|
||||
var stream = await resp.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
|
||||
var data = await JsonSerializer.DeserializeAsync<KickChannelResponse>(stream, cancellationToken: ct)
|
||||
.ConfigureAwait(false);
|
||||
if (data != null)
|
||||
return data;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Kanal bilgisi alınamadı ({channelName}, {baseUrl}): {ex.Message}");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Master HLS playlist (.m3u8) içinden istenen kaliteye (1080p, 720p60, 480p vb.) ait doğrudan akış URL'sini seçer.
|
||||
/// </summary>
|
||||
public async Task<string> ResolveQualityUrlAsync(string masterPlaylistUrl, string quality, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(masterPlaylistUrl) ||
|
||||
string.IsNullOrWhiteSpace(quality) ||
|
||||
quality.Equals("best", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return masterPlaylistUrl;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var resp = await Http.GetAsync(masterPlaylistUrl, ct).ConfigureAwait(false);
|
||||
if (!resp.IsSuccessStatusCode) return masterPlaylistUrl;
|
||||
|
||||
var m3u8 = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
var regex = new Regex(@"#EXT-X-STREAM-INF:([^\r\n]+)[\r\n]+([^\r\n]+)");
|
||||
var matches = regex.Matches(m3u8);
|
||||
|
||||
string? bestMatchUrl = null;
|
||||
var cleanQuality = quality.ToLowerInvariant().Replace("p", "").Replace("60", "").Replace("30", "");
|
||||
|
||||
foreach (Match match in matches)
|
||||
{
|
||||
var info = match.Groups[1].Value;
|
||||
var streamUrl = match.Groups[2].Value.Trim();
|
||||
|
||||
if (info.Contains(quality, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return streamUrl;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(cleanQuality) && info.Contains(cleanQuality, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
bestMatchUrl ??= streamUrl;
|
||||
}
|
||||
}
|
||||
|
||||
return bestMatchUrl ?? masterPlaylistUrl;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Kalite playlisti ayrıştırılamadı ({quality}): {ex.Message}");
|
||||
return masterPlaylistUrl;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]?> GetImageBytesAsync(string url, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var resp = await Http.GetAsync(url, ct).ConfigureAwait(false);
|
||||
if (!resp.IsSuccessStatusCode) return null;
|
||||
return await resp.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Görsel indirilemedi ({url}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
using System.Collections.Concurrent;
|
||||
using KickStreamHub.Models;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
public class LiveStatusResultEventArgs : EventArgs
|
||||
{
|
||||
public IReadOnlyDictionary<string, ChannelStatus> Results { get; }
|
||||
public LiveStatusResultEventArgs(IReadOnlyDictionary<string, ChannelStatus> results) => Results = results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Favori kanalların canlı yayın durumunu belirli aralıklarla, sınırlı
|
||||
/// eşzamanlılıkla (SemaphoreSlim) sorgular. .NET HttpClient thread-safe
|
||||
/// olduğu için burada onlarca kanal aynı anda güvenle sorgulanabilir.
|
||||
/// </summary>
|
||||
public sealed class LiveStatusPollingService : IDisposable
|
||||
{
|
||||
private readonly KickApiService _api;
|
||||
private readonly SemaphoreSlim _concurrencyLimiter = new(6);
|
||||
private System.Threading.Timer? _timer;
|
||||
private int _isPolling;
|
||||
private IReadOnlyList<string> _channels = Array.Empty<string>();
|
||||
|
||||
public event EventHandler<LiveStatusResultEventArgs>? ResultsReady;
|
||||
public event EventHandler<string>? StatusMessage;
|
||||
|
||||
public LiveStatusPollingService(KickApiService api)
|
||||
{
|
||||
_api = api;
|
||||
}
|
||||
|
||||
public void UpdateChannelList(IReadOnlyList<string> channels) => _channels = channels;
|
||||
|
||||
public void Start(int intervalSeconds)
|
||||
{
|
||||
Stop();
|
||||
_timer = new System.Threading.Timer(async _ => await PollOnceSafeAsync().ConfigureAwait(false),
|
||||
null, TimeSpan.Zero, TimeSpan.FromSeconds(intervalSeconds));
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
}
|
||||
|
||||
public Task RefreshNowAsync() => PollOnceSafeAsync(isManual: true);
|
||||
|
||||
private async Task PollOnceSafeAsync(bool isManual = false)
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _isPolling, 1, 0) != 0) return;
|
||||
try
|
||||
{
|
||||
await PollOnceAsync(isManual).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Error("Canlı yayın kontrolü sırasında hata", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _isPolling, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PollOnceAsync(bool isManual = false)
|
||||
{
|
||||
var channels = _channels;
|
||||
if (channels.Count == 0) return;
|
||||
|
||||
if (isManual)
|
||||
{
|
||||
StatusMessage?.Invoke(this, $"{channels.Count} kanal sorgulanıyor...");
|
||||
}
|
||||
var results = new ConcurrentDictionary<string, ChannelStatus>();
|
||||
|
||||
var tasks = channels.Select(async channel =>
|
||||
{
|
||||
await _concurrencyLimiter.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var status = await FetchOneAsync(channel).ConfigureAwait(false);
|
||||
results[channel] = status;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_concurrencyLimiter.Release();
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
|
||||
ResultsReady?.Invoke(this, new LiveStatusResultEventArgs(results));
|
||||
StatusMessage?.Invoke(this, $"✔ {channels.Count} kanal güncellendi.");
|
||||
}
|
||||
|
||||
private async Task<ChannelStatus> FetchOneAsync(string channel)
|
||||
{
|
||||
var data = await _api.GetChannelAsync(channel).ConfigureAwait(false);
|
||||
if (data is null)
|
||||
{
|
||||
return new ChannelStatus { ChannelName = channel, FetchSucceeded = false };
|
||||
}
|
||||
|
||||
var live = data.Livestream;
|
||||
return new ChannelStatus
|
||||
{
|
||||
ChannelName = channel,
|
||||
IsLive = live is not null,
|
||||
Title = live?.SessionTitle ?? string.Empty,
|
||||
Category = live?.Categories?.FirstOrDefault()?.Name ?? string.Empty,
|
||||
Viewers = live?.ViewerCount ?? 0,
|
||||
Verified = data.Verified,
|
||||
ProfilePicUrl = data.User?.ProfilePic ?? string.Empty,
|
||||
PlaybackUrl = data.PlaybackUrl ?? string.Empty,
|
||||
ChatroomId = data.Chatroom?.Id,
|
||||
FetchSucceeded = true,
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
_concurrencyLimiter.Dispose();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
public enum LogLevel { Info, Warning, Error }
|
||||
|
||||
/// <summary>
|
||||
/// Basit, dosya tabanlı, iş parçacığı güvenli (thread-safe) log servisi.
|
||||
/// %LOCALAPPDATA%\KickStreamHub\logs\app.log dosyasına yazar ve
|
||||
/// belirli bir boyutu (5 MB) aştığında dosyayı döndürür (rotate).
|
||||
/// </summary>
|
||||
public sealed class LoggingService
|
||||
{
|
||||
private static readonly Lazy<LoggingService> _instance = new(() => new LoggingService());
|
||||
public static LoggingService Instance => _instance.Value;
|
||||
|
||||
private readonly string _logFilePath;
|
||||
private readonly object _lock = new();
|
||||
private const long MaxSizeBytes = 5 * 1024 * 1024;
|
||||
|
||||
private LoggingService()
|
||||
{
|
||||
var dir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LDKickWatch", "logs");
|
||||
Directory.CreateDirectory(dir);
|
||||
_logFilePath = Path.Combine(dir, "app.log");
|
||||
}
|
||||
|
||||
public void Info(string message) => Write(LogLevel.Info, message);
|
||||
public void Warning(string message) => Write(LogLevel.Warning, message);
|
||||
public void Error(string message, Exception? ex = null) =>
|
||||
Write(LogLevel.Error, ex is null ? message : $"{message} :: {ex}");
|
||||
|
||||
private void Write(LogLevel level, string message)
|
||||
{
|
||||
var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}";
|
||||
lock (_lock)
|
||||
{
|
||||
try
|
||||
{
|
||||
RotateIfNeeded();
|
||||
File.AppendAllText(_logFilePath, line + Environment.NewLine, Encoding.UTF8);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Loglama asla uygulamayı çökertmemeli.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RotateIfNeeded()
|
||||
{
|
||||
if (!File.Exists(_logFilePath)) return;
|
||||
var info = new FileInfo(_logFilePath);
|
||||
if (info.Length < MaxSizeBytes) return;
|
||||
var backup = Path.ChangeExtension(_logFilePath, ".1.log");
|
||||
try
|
||||
{
|
||||
if (File.Exists(backup)) File.Delete(backup);
|
||||
File.Move(_logFilePath, backup);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// yoksay
|
||||
}
|
||||
}
|
||||
|
||||
public string LogDirectory => Path.GetDirectoryName(_logFilePath)!;
|
||||
}
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
using System.Windows.Forms;
|
||||
using Application = System.Windows.Application;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Sistem tepsisi simgesini ve bildirimleri (balloon tip) yönetir.
|
||||
/// </summary>
|
||||
public sealed class NotificationService : IDisposable
|
||||
{
|
||||
private readonly NotifyIcon _notifyIcon;
|
||||
|
||||
public event EventHandler? OpenRequested;
|
||||
public event EventHandler? ExitRequested;
|
||||
|
||||
public NotificationService()
|
||||
{
|
||||
System.Drawing.Icon? customIcon = null;
|
||||
try
|
||||
{
|
||||
var streamInfo = Application.GetResourceStream(new Uri("pack://application:,,,/Resources/app.ico"));
|
||||
if (streamInfo?.Stream != null)
|
||||
{
|
||||
customIcon = new System.Drawing.Icon(streamInfo.Stream);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
_notifyIcon = new NotifyIcon
|
||||
{
|
||||
Icon = customIcon ?? System.Drawing.SystemIcons.Application,
|
||||
Text = "LD KickWatch",
|
||||
Visible = false,
|
||||
};
|
||||
|
||||
var menu = new ContextMenuStrip();
|
||||
menu.Items.Add("LD KickWatch'u Göster", null, (_, _) => OpenRequested?.Invoke(this, EventArgs.Empty));
|
||||
menu.Items.Add(new ToolStripSeparator());
|
||||
menu.Items.Add("Çıkış", null, (_, _) => ExitRequested?.Invoke(this, EventArgs.Empty));
|
||||
_notifyIcon.ContextMenuStrip = menu;
|
||||
|
||||
_notifyIcon.DoubleClick += (_, _) => OpenRequested?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public void Show() => _notifyIcon.Visible = true;
|
||||
public void Hide() => _notifyIcon.Visible = false;
|
||||
|
||||
public void ShowBalloon(string title, string text)
|
||||
{
|
||||
try
|
||||
{
|
||||
_notifyIcon.BalloonTipTitle = title;
|
||||
_notifyIcon.BalloonTipText = text;
|
||||
_notifyIcon.ShowBalloonTip(6000);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// bildirim gösterilemezse sessizce yoksay
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
_notifyIcon.Visible = false;
|
||||
_notifyIcon.Dispose();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,273 +0,0 @@
|
|||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
public class ChatMessageEventArgs : EventArgs
|
||||
{
|
||||
public string Username { get; init; } = string.Empty;
|
||||
public string Message { get; init; } = string.Empty;
|
||||
public string RawMessage { get; init; } = string.Empty;
|
||||
public string ColorHex { get; init; } = "#53FC18";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kick.com sohbetinin Pusher WebSocket protokolüne bağlanan istemci.
|
||||
/// .NET'in ClientWebSocket'i tek bir dedike okuma döngüsünde asenkron
|
||||
/// olarak kullanıldığından, Python tarafındaki gibi çoklu iş parçacığı
|
||||
/// çakışması riski yoktur. Bağlantı koptuğunda üstel geri çekilmeyle
|
||||
/// (exponential backoff) otomatik olarak yeniden bağlanır.
|
||||
/// </summary>
|
||||
public sealed partial class PusherChatService : IAsyncDisposable
|
||||
{
|
||||
private static string s_activeAppKey = "34bf7a0ff419a2a775b9";
|
||||
private static string s_activeCluster = "us2";
|
||||
|
||||
[GeneratedRegex(@"\[emote:\d+:([^\]]+)\]")]
|
||||
private static partial Regex KickEmoteRegex();
|
||||
|
||||
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
||||
private ClientWebSocket? _socket;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _receiveLoopTask;
|
||||
private long _chatroomId;
|
||||
private int _reconnectAttempt;
|
||||
|
||||
public event EventHandler<ChatMessageEventArgs>? MessageReceived;
|
||||
public event EventHandler<bool>? ConnectionStateChanged;
|
||||
|
||||
public async Task ConnectAsync(long chatroomId)
|
||||
{
|
||||
await DisconnectAsync().ConfigureAwait(false);
|
||||
_chatroomId = chatroomId;
|
||||
_cts = new CancellationTokenSource();
|
||||
_receiveLoopTask = RunConnectionLoopAsync(_cts.Token);
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_cts?.Cancel();
|
||||
if (_socket is { State: WebSocketState.Open })
|
||||
{
|
||||
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "closing", CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// kapatma sırasında oluşan hatalar yoksayılır
|
||||
}
|
||||
finally
|
||||
{
|
||||
_socket?.Dispose();
|
||||
_socket = null;
|
||||
if (_receiveLoopTask != null)
|
||||
{
|
||||
try { await _receiveLoopTask.ConfigureAwait(false); } catch { /* yoksay */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunConnectionLoopAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ConnectOnceAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Sohbet bağlantısı kesildi: {ex.Message}");
|
||||
}
|
||||
|
||||
ConnectionStateChanged?.Invoke(this, false);
|
||||
if (ct.IsCancellationRequested) break;
|
||||
|
||||
_reconnectAttempt++;
|
||||
var delay = TimeSpan.FromSeconds(Math.Min(30, Math.Pow(2, _reconnectAttempt)));
|
||||
try { await Task.Delay(delay, ct).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) { break; }
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ConnectOnceAsync(CancellationToken ct)
|
||||
{
|
||||
_socket = new ClientWebSocket();
|
||||
var uri = new Uri($"wss://ws-{s_activeCluster}.pusher.com/app/{s_activeAppKey}?protocol=7&client=js&version=8.4.0&flash=false");
|
||||
await _socket.ConnectAsync(uri, ct).ConfigureAwait(false);
|
||||
_reconnectAttempt = 0;
|
||||
ConnectionStateChanged?.Invoke(this, true);
|
||||
|
||||
var buffer = new byte[16384];
|
||||
var messageBuilder = new StringBuilder();
|
||||
using var pingCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var pingTask = RunPingLoopAsync(pingCts.Token);
|
||||
|
||||
try
|
||||
{
|
||||
while (_socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
|
||||
{
|
||||
messageBuilder.Clear();
|
||||
WebSocketReceiveResult result;
|
||||
do
|
||||
{
|
||||
result = await _socket.ReceiveAsync(new ArraySegment<byte>(buffer), ct).ConfigureAwait(false);
|
||||
if (result.MessageType == WebSocketMessageType.Close) return;
|
||||
messageBuilder.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));
|
||||
} while (!result.EndOfMessage);
|
||||
|
||||
await HandleRawMessageAsync(messageBuilder.ToString(), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
pingCts.Cancel();
|
||||
try { await pingTask.ConfigureAwait(false); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunPingLoopAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
|
||||
if (_socket is { State: WebSocketState.Open })
|
||||
{
|
||||
await SendAsync("{\"event\":\"pusher:ping\",\"data\":{}}", ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Sohbet ping gönderilemedi: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleRawMessageAsync(string raw, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(raw);
|
||||
var root = doc.RootElement;
|
||||
var eventName = root.TryGetProperty("event", out var evEl) ? evEl.GetString() : null;
|
||||
|
||||
switch (eventName)
|
||||
{
|
||||
case "pusher:connection_established":
|
||||
await SubscribeToChatroomAsync(ct).ConfigureAwait(false);
|
||||
break;
|
||||
|
||||
case "App\\Events\\ChatMessageEvent":
|
||||
case "ChatMessageEvent":
|
||||
HandleChatMessagePayload(root);
|
||||
break;
|
||||
|
||||
case "pusher:ping":
|
||||
await SendAsync("{\"event\":\"pusher:pong\",\"data\":{}}", ct).ConfigureAwait(false);
|
||||
break;
|
||||
|
||||
case "pusher:error":
|
||||
LoggingService.Instance.Warning($"Pusher sohbet hatası: {raw}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Sohbet mesajı ayrıştırılamadı: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleChatMessagePayload(JsonElement root)
|
||||
{
|
||||
try
|
||||
{
|
||||
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,
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Sohbet yükü işlenemedi: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SubscribeToChatroomAsync(CancellationToken ct)
|
||||
{
|
||||
var channelName = $"chatrooms.{_chatroomId}.v2";
|
||||
var payload = JsonSerializer.Serialize(new
|
||||
{
|
||||
@event = "pusher:subscribe",
|
||||
data = new { auth = "", channel = channelName },
|
||||
});
|
||||
await SendAsync(payload, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task SendAsync(string json, CancellationToken ct)
|
||||
{
|
||||
if (_socket is not { State: WebSocketState.Open }) return;
|
||||
await _sendLock.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_socket is not { State: WebSocketState.Open }) return;
|
||||
var bytes = Encoding.UTF8.GetBytes(json);
|
||||
await _socket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_sendLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await DisconnectAsync().ConfigureAwait(false);
|
||||
_cts?.Dispose();
|
||||
_sendLock.Dispose();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
public static class ShortcutService
|
||||
{
|
||||
public static bool CreateDesktopShortcut(out string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
var exePath = Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule?.FileName;
|
||||
if (string.IsNullOrEmpty(exePath) || !File.Exists(exePath))
|
||||
{
|
||||
message = "Uygulama yürütülebilir dosyası bulunamadı.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var shellType = Type.GetTypeFromProgID("WScript.Shell");
|
||||
if (shellType == null)
|
||||
{
|
||||
message = "Windows Script Shell servisine ulaşılamadı.";
|
||||
return false;
|
||||
}
|
||||
|
||||
dynamic? shell = Activator.CreateInstance(shellType);
|
||||
if (shell == null)
|
||||
{
|
||||
message = "Kısayol oluşturucu başlatılamadı.";
|
||||
return false;
|
||||
}
|
||||
|
||||
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
|
||||
string shortcutPath = Path.Combine(desktopPath, "LD KickWatch.lnk");
|
||||
|
||||
dynamic shortcut = shell.CreateShortcut(shortcutPath);
|
||||
shortcut.TargetPath = exePath;
|
||||
shortcut.WorkingDirectory = Path.GetDirectoryName(exePath) ?? "";
|
||||
shortcut.Description = "LD KickWatch - Kick.com Canlı Yayın İzleme Stüdyosu";
|
||||
shortcut.IconLocation = $"{exePath},0";
|
||||
shortcut.Save();
|
||||
|
||||
message = "Masaüstü kısayolu başarıyla oluşturuldu!";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
message = $"Kısayol oluşturulurken hata oluştu: {ex.Message}";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
using System.IO;
|
||||
using System.Media;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Canlı yayın başlangıcı, kategori değişikliği ve anahtar kelime uyarıları için
|
||||
/// sesli bildirim çalar. Özel .wav dosyası seçilmemişse bellekte yumuşak çift tonlu
|
||||
/// bir bildirim sesi (chime) üretip çalar.
|
||||
/// </summary>
|
||||
public static class SoundService
|
||||
{
|
||||
private static readonly byte[] DefaultChimeWav = GeneratePleasantChimeWav(587.33, 880.0, 260); // D5 -> A5
|
||||
private static readonly byte[] KeywordAlertWav = GeneratePleasantChimeWav(659.25, 1046.50, 300); // E5 -> C6
|
||||
|
||||
public static void PlayNotification(string? customSoundPath = null, bool isKeywordOrCategoryAlert = false)
|
||||
{
|
||||
Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(customSoundPath) && File.Exists(customSoundPath))
|
||||
{
|
||||
using var player = new SoundPlayer(customSoundPath);
|
||||
player.PlaySync();
|
||||
return;
|
||||
}
|
||||
|
||||
var wavBytes = isKeywordOrCategoryAlert ? KeywordAlertWav : DefaultChimeWav;
|
||||
using var ms = new MemoryStream(wavBytes);
|
||||
using var chimePlayer = new SoundPlayer(ms);
|
||||
chimePlayer.PlaySync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LoggingService.Instance.Warning($"Bildirim sesi çalınamadı: {ex.Message}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static byte[] GeneratePleasantChimeWav(double freq1, double freq2, int durationMs)
|
||||
{
|
||||
const int sampleRate = 44100;
|
||||
int totalSamples = sampleRate * durationMs / 1000;
|
||||
int halfSamples = totalSamples / 2;
|
||||
|
||||
using var ms = new MemoryStream();
|
||||
using var bw = new BinaryWriter(ms);
|
||||
|
||||
int dataSize = totalSamples * 2;
|
||||
bw.Write("RIFF"u8.ToArray());
|
||||
bw.Write(36 + dataSize);
|
||||
bw.Write("WAVE"u8.ToArray());
|
||||
bw.Write("fmt "u8.ToArray());
|
||||
bw.Write(16);
|
||||
bw.Write((short)1); // PCM
|
||||
bw.Write((short)1); // Mono
|
||||
bw.Write(sampleRate);
|
||||
bw.Write(sampleRate * 2);
|
||||
bw.Write((short)2);
|
||||
bw.Write((short)16);
|
||||
bw.Write("data"u8.ToArray());
|
||||
bw.Write(dataSize);
|
||||
|
||||
for (int i = 0; i < totalSamples; i++)
|
||||
{
|
||||
double freq = i < halfSamples ? freq1 : freq2;
|
||||
int localIndex = i < halfSamples ? i : i - halfSamples;
|
||||
int localLen = i < halfSamples ? halfSamples : totalSamples - halfSamples;
|
||||
|
||||
double t = (double)localIndex / sampleRate;
|
||||
double envelope = Math.Exp(-4.5 * localIndex / localLen);
|
||||
if (localIndex < 200) envelope *= localIndex / 200.0;
|
||||
|
||||
double sample = Math.Sin(2 * Math.PI * freq * t) * 0.35 * envelope;
|
||||
short pcm = (short)(sample * short.MaxValue);
|
||||
bw.Write(pcm);
|
||||
}
|
||||
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,276 +0,0 @@
|
|||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace KickStreamHub.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Pencere İçi VLC, Harici VLC ve Harici MPV işlemlerini bulan, başlatan ve
|
||||
/// izleyen servis.
|
||||
/// </summary>
|
||||
public sealed class StreamlinkService
|
||||
{
|
||||
private readonly Dictionary<string, Process> _activeProcesses = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Process? _embeddedVlcProcess;
|
||||
private string? _embeddedVlcChannel;
|
||||
private readonly object _lock = new();
|
||||
|
||||
public event EventHandler<string>? ProcessExited;
|
||||
|
||||
public string? FindStreamlink(string? configuredPath)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(configuredPath) && File.Exists(configuredPath))
|
||||
return configuredPath;
|
||||
|
||||
var candidates = new List<string>
|
||||
{
|
||||
"streamlink.exe",
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Streamlink", "bin", "streamlink.exe"),
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Streamlink", "bin", "streamlink.exe"),
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Streamlink", "bin", "streamlink.exe"),
|
||||
};
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
var resolved = ResolveFromPathOrFile(candidate);
|
||||
if (resolved != null) return resolved;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public string? FindPlayer(string playerChoice, string? configuredPath)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(configuredPath) && File.Exists(configuredPath))
|
||||
return configuredPath;
|
||||
|
||||
bool isMpv = playerChoice.Equals("mpv", StringComparison.OrdinalIgnoreCase);
|
||||
var names = isMpv ? new[] { "mpv.exe" } : new[] { "vlc.exe" };
|
||||
|
||||
var programFiles = new[]
|
||||
{
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
|
||||
};
|
||||
|
||||
foreach (var name in names)
|
||||
{
|
||||
var resolved = ResolveFromPathOrFile(name);
|
||||
if (resolved != null) return resolved;
|
||||
|
||||
foreach (var pf in programFiles)
|
||||
{
|
||||
var candidate = Path.Combine(pf, isMpv ? "mpv" : "VideoLAN\\VLC", name);
|
||||
if (File.Exists(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? ResolveFromPathOrFile(string nameOrPath)
|
||||
{
|
||||
if (File.Exists(nameOrPath)) return Path.GetFullPath(nameOrPath);
|
||||
|
||||
var pathEnv = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
|
||||
foreach (var dir in pathEnv.Split(Path.PathSeparator))
|
||||
{
|
||||
try
|
||||
{
|
||||
var full = Path.Combine(dir, nameOrPath);
|
||||
if (File.Exists(full)) return full;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// geçersiz path parçalarını yoksay
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public bool IsPlaying(string channelName)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_embeddedVlcProcess is { HasExited: false } &&
|
||||
string.Equals(_embeddedVlcChannel, channelName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_activeProcesses.TryGetValue(channelName, out var proc))
|
||||
{
|
||||
if (!proc.HasExited) return true;
|
||||
_activeProcesses.Remove(channelName);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VLC'yi doğrudan uygulama penceresi içindeki WinForms Panel HWND'sine (--drawable-hwnd) gömer.
|
||||
/// Doğrudan HLS akış linkiyle başlatıldığı için anında (0.3 saniyede) açılır, Cloudflare/Streamlink engeline takılmaz.
|
||||
/// </summary>
|
||||
public (bool success, string message) PlayEmbeddedVlc(
|
||||
string channelName,
|
||||
IntPtr hwnd,
|
||||
string vlcPath,
|
||||
string streamUrl,
|
||||
string? extraArgs = null)
|
||||
{
|
||||
StopEmbeddedVlc();
|
||||
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(streamUrl))
|
||||
{
|
||||
return (false, $"🔴 {channelName.ToUpperInvariant()} için canlı yayın akış linki bulunamadı.");
|
||||
}
|
||||
|
||||
var args = $"\"{streamUrl}\" -I dummy --dummy-quiet --drawable-hwnd={hwnd.ToInt64()} --no-video-title-show --network-caching=800 --clock-jitter=0 --no-sub-autodetect-file";
|
||||
if (!string.IsNullOrWhiteSpace(extraArgs))
|
||||
{
|
||||
args += $" {extraArgs.Trim()}";
|
||||
}
|
||||
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = vlcPath,
|
||||
Arguments = args,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
WindowStyle = ProcessWindowStyle.Hidden,
|
||||
};
|
||||
|
||||
var process = Process.Start(psi);
|
||||
if (process is null) return (false, "Pencere içi VLC başlatılamadı.");
|
||||
|
||||
// Windows Job Object'e bağla: Uygulama kapatıldığında VLC asla arkada açık kalmaz
|
||||
Helpers.ChildProcessTracker.AddProcess(process);
|
||||
|
||||
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'de açı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ı.");
|
||||
|
||||
Helpers.ChildProcessTracker.AddProcess(process);
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
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";
|
||||
}
|
||||
|
|
@ -1,172 +0,0 @@
|
|||
using System.Collections.Concurrent;
|
||||
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;
|
||||
private readonly ConcurrentQueue<ChatMessageItem> _incomingQueue = new();
|
||||
private readonly DispatcherTimer _batchTimer;
|
||||
|
||||
public int MaxMessages { get; set; } = 500;
|
||||
|
||||
[ObservableProperty] private string _channelName = string.Empty;
|
||||
[ObservableProperty] private long _chatroomId;
|
||||
[ObservableProperty] private bool _isConnected;
|
||||
[ObservableProperty] private bool _isPaused;
|
||||
[ObservableProperty] private string _filterText = string.Empty;
|
||||
[ObservableProperty] private double _fontSize = 13;
|
||||
[ObservableProperty] private double _backgroundOpacity = 1.0;
|
||||
[ObservableProperty] private bool _isTopMost;
|
||||
[ObservableProperty] private int _messageCount;
|
||||
|
||||
public ObservableCollection<ChatMessageItem> Messages { get; } = new();
|
||||
public ObservableCollection<ChatMessageItem> FilteredMessages { get; } = new();
|
||||
|
||||
public event EventHandler? NewMessagesAppended;
|
||||
|
||||
public ChatViewModel()
|
||||
{
|
||||
_dispatcher = Dispatcher.CurrentDispatcher;
|
||||
_chatService.MessageReceived += OnMessageReceived;
|
||||
_chatService.ConnectionStateChanged += (_, connected) =>
|
||||
_dispatcher.BeginInvoke(() => IsConnected = connected);
|
||||
|
||||
_batchTimer = new DispatcherTimer(DispatcherPriority.Background, _dispatcher)
|
||||
{
|
||||
Interval = TimeSpan.FromMilliseconds(75)
|
||||
};
|
||||
_batchTimer.Tick += BatchTimer_Tick;
|
||||
_batchTimer.Start();
|
||||
}
|
||||
|
||||
private void BatchTimer_Tick(object? sender, EventArgs e)
|
||||
{
|
||||
if (_incomingQueue.IsEmpty) return;
|
||||
|
||||
bool hasAppended = false;
|
||||
int processed = 0;
|
||||
while (_incomingQueue.TryDequeue(out var item) && processed < 40)
|
||||
{
|
||||
processed++;
|
||||
Messages.Add(item);
|
||||
while (Messages.Count > MaxMessages)
|
||||
Messages.RemoveAt(0);
|
||||
|
||||
if (!IsPaused && MatchesFilter(item))
|
||||
{
|
||||
FilteredMessages.Add(item);
|
||||
while (FilteredMessages.Count > MaxMessages)
|
||||
FilteredMessages.RemoveAt(0);
|
||||
hasAppended = true;
|
||||
}
|
||||
}
|
||||
|
||||
MessageCount = Messages.Count;
|
||||
|
||||
if (hasAppended && !IsPaused)
|
||||
{
|
||||
NewMessagesAppended?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ConnectAsync(string channelName, long chatroomId)
|
||||
{
|
||||
if (IsConnected && ChatroomId == chatroomId && string.Equals(ChannelName, channelName, StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
|
||||
ChannelName = channelName;
|
||||
ChatroomId = chatroomId;
|
||||
|
||||
while (_incomingQueue.TryDequeue(out _)) { }
|
||||
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)
|
||||
{
|
||||
try
|
||||
{
|
||||
var item = new ChatMessageItem
|
||||
{
|
||||
Username = e.Username,
|
||||
Message = e.Message,
|
||||
RawMessage = string.IsNullOrEmpty(e.RawMessage) ? e.Message : e.RawMessage,
|
||||
ColorHex = e.ColorHex,
|
||||
};
|
||||
|
||||
_incomingQueue.Enqueue(item);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
while (_incomingQueue.TryDequeue(out _)) { }
|
||||
Messages.Clear();
|
||||
FilteredMessages.Clear();
|
||||
MessageCount = 0;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_batchTimer.Stop();
|
||||
await _chatService.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
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;
|
||||
}
|
||||
|
|
@ -1,119 +0,0 @@
|
|||
<Window x:Class="KickStreamHub.Views.ChatWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:helpers="clr-namespace:KickStreamHub.Helpers"
|
||||
Title="{Binding ChannelName, StringFormat='{}{0} — Canlı Sohbet (LD KickWatch)'}"
|
||||
Icon="pack://application:,,,/Resources/app.ico"
|
||||
Height="680" Width="430" MinWidth="320" MinHeight="420"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Topmost="{Binding IsTopMost}" ResizeMode="CanResizeWithGrip"
|
||||
Opacity="{Binding BackgroundOpacity}"
|
||||
Background="#060A10">
|
||||
<Grid Margin="12">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Row 0: Chat Header -->
|
||||
<Border Grid.Row="0" Background="#0D141F" CornerRadius="10" Padding="12,8" Margin="0,0,0,8" BorderBrush="#1C283B" BorderThickness="1">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock FontSize="15" FontWeight="ExtraBold" Foreground="#53FC18"
|
||||
Text="{Binding ChannelName, StringFormat='💬 {0}'}" VerticalAlignment="Center" />
|
||||
<Border Background="#152234" CornerRadius="6" Padding="7,2" Margin="10,0,0,0" VerticalAlignment="Center">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Ellipse Width="7" Height="7" Margin="0,0,5,0" VerticalAlignment="Center"
|
||||
Fill="{Binding IsConnected, Converter={StaticResource LiveToBrush}}" />
|
||||
<TextBlock Foreground="#CBD5E1" FontSize="10.5" FontWeight="SemiBold" VerticalAlignment="Center"
|
||||
Text="{Binding IsConnected, Converter={StaticResource ChatConnTextConverter}}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<CheckBox Grid.Column="1" Content="📌 Üstte Tut" Foreground="#CBD5E1" FontSize="11.5" VerticalAlignment="Center"
|
||||
IsChecked="{Binding IsTopMost}" ToolTip="Pencereyi her zaman üstte tut" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Row 1: Filter & Controls -->
|
||||
<Grid Grid.Row="1" Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox Grid.Column="0" Margin="0,0,6,0" FontSize="12"
|
||||
Tag="🔍 Mesaj veya kullanıcı ara..."
|
||||
Text="{Binding FilterText, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<Button Grid.Column="1" Content="{Binding IsPaused, Converter={StaticResource PauseTextConverter}}"
|
||||
Style="{StaticResource SecondaryButton}" Margin="0,0,5,0"
|
||||
Command="{Binding TogglePauseCommand}" Padding="10,6" FontSize="11" />
|
||||
<Button Grid.Column="2" Content="🗑" Style="{StaticResource DangerButton}"
|
||||
Command="{Binding ClearMessagesCommand}" Padding="9,6" FontSize="11" ToolTip="Sohbeti Temizle" />
|
||||
</Grid>
|
||||
|
||||
<!-- Row 2: Messages List -->
|
||||
<Border Grid.Row="2" Background="#0A0F17" BorderBrush="#1A2638" BorderThickness="1" CornerRadius="10" Padding="4">
|
||||
<ListBox x:Name="ChatListBox"
|
||||
ItemsSource="{Binding FilteredMessages}"
|
||||
Background="Transparent" BorderThickness="0"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
|
||||
ScrollViewer.CanContentScroll="False"
|
||||
VirtualizingPanel.ScrollUnit="Pixel">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Background="#0E1520" CornerRadius="6" Padding="8,5" Margin="2,2">
|
||||
<TextBlock TextWrapping="Wrap"
|
||||
FontSize="{Binding DataContext.FontSize, RelativeSource={RelativeSource AncestorType=Window}}"
|
||||
helpers:RichChatHelper.MessageItem="{Binding}" />
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
<ListBox.ItemContainerStyle>
|
||||
<Style TargetType="ListBoxItem">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="Margin" Value="0" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="Focusable" Value="False" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ListBoxItem">
|
||||
<ContentPresenter />
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</ListBox.ItemContainerStyle>
|
||||
</ListBox>
|
||||
</Border>
|
||||
|
||||
<!-- Row 3: Font & Opacity Sliders -->
|
||||
<Border Grid.Row="3" Background="#0D141F" CornerRadius="8" Padding="10,7" Margin="0,8,0,0" BorderBrush="#1C283B" BorderThickness="1">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="🔠 Boyut:" Foreground="#94A3B8" FontSize="11" VerticalAlignment="Center" Margin="0,0,6,0" />
|
||||
<Slider Grid.Column="1" Minimum="10" Maximum="22" Value="{Binding FontSize}"
|
||||
TickFrequency="1" IsSnapToTickEnabled="True" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="2" Text="👁 Saydamlık:" Foreground="#94A3B8" FontSize="11"
|
||||
VerticalAlignment="Center" Margin="12,0,6,0" />
|
||||
<Slider Grid.Column="3" Minimum="0.35" Maximum="1.0" Value="{Binding BackgroundOpacity}"
|
||||
TickFrequency="0.05" IsSnapToTickEnabled="True" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
using System.Collections.Specialized;
|
||||
using System.Windows;
|
||||
using KickStreamHub.ViewModels;
|
||||
|
||||
namespace KickStreamHub.Views;
|
||||
|
||||
public partial class ChatWindow : Window
|
||||
{
|
||||
private readonly ChatViewModel _vm;
|
||||
|
||||
public ChatWindow(string channelName, long chatroomId, int maxMessages = 500)
|
||||
{
|
||||
InitializeComponent();
|
||||
_vm = new ChatViewModel { MaxMessages = maxMessages };
|
||||
DataContext = _vm;
|
||||
|
||||
Loaded += async (_, _) => await _vm.ConnectAsync(channelName, chatroomId);
|
||||
Closed += async (_, _) => await _vm.DisposeAsync();
|
||||
|
||||
_vm.NewMessagesAppended += (_, _) => AutoScrollToBottom();
|
||||
}
|
||||
|
||||
private void AutoScrollToBottom()
|
||||
{
|
||||
if (_vm.IsPaused) return;
|
||||
|
||||
try
|
||||
{
|
||||
if (ChatListBox.Items.Count > 0)
|
||||
{
|
||||
ChatListBox.ScrollIntoView(ChatListBox.Items[^1]);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,543 +0,0 @@
|
|||
using System.Collections.Specialized;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using KickStreamHub.Services;
|
||||
using KickStreamHub.ViewModels;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Microsoft.Web.WebView2.Wpf;
|
||||
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
|
||||
using SaveFileDialog = Microsoft.Win32.SaveFileDialog;
|
||||
|
||||
namespace KickStreamHub.Views;
|
||||
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
private readonly MainViewModel _viewModel;
|
||||
private readonly NotificationService _notifications;
|
||||
private bool _isWebViewInitialized;
|
||||
private readonly bool[] _isMultiWebViewInitialized = new bool[4];
|
||||
private CoreWebView2Environment? _webViewEnv;
|
||||
private WindowState _stateBeforeFullScreen = WindowState.Normal;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
VlcPanel.BackColor = System.Drawing.Color.FromArgb(4, 9, 15);
|
||||
|
||||
_viewModel = new MainViewModel();
|
||||
_notifications = new NotificationService();
|
||||
_viewModel.Notifications = _notifications;
|
||||
DataContext = _viewModel;
|
||||
|
||||
_viewModel.EmbeddedPlayRequested += ViewModel_EmbeddedPlayRequested;
|
||||
_viewModel.EmbeddedVlcPlayRequested += ViewModel_EmbeddedVlcPlayRequested;
|
||||
_viewModel.EmbeddedStopRequested += ViewModel_EmbeddedStopRequested;
|
||||
_viewModel.EmbeddedMuteRequested += ViewModel_EmbeddedMuteRequested;
|
||||
_viewModel.EmbeddedReloadRequested += ViewModel_EmbeddedReloadRequested;
|
||||
_viewModel.FullScreenChanged += ViewModel_FullScreenChanged;
|
||||
|
||||
_viewModel.MultiSlotPlayRequested += ViewModel_MultiSlotPlayRequested;
|
||||
_viewModel.MultiSlotStopRequested += ViewModel_MultiSlotStopRequested;
|
||||
_viewModel.MultiSlotMuteRequested += ViewModel_MultiSlotMuteRequested;
|
||||
|
||||
_viewModel.EmbeddedChat.NewMessagesAppended += EmbeddedChat_NewMessagesAppended;
|
||||
|
||||
_notifications.OpenRequested += (_, _) => RestoreAndBringToFront();
|
||||
_notifications.ExitRequested += (_, _) => Close();
|
||||
_notifications.Show();
|
||||
|
||||
Loaded += (_, _) => _viewModel.Start();
|
||||
StateChanged += MainWindow_StateChanged;
|
||||
Closing += MainWindow_Closing;
|
||||
|
||||
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
|
||||
|
||||
RestoreWindowBounds();
|
||||
|
||||
var ctrlF = new KeyBinding(new RelayFocusCommand(this), Key.F, ModifierKeys.Control);
|
||||
InputBindings.Add(ctrlF);
|
||||
}
|
||||
|
||||
private async Task<CoreWebView2Environment> GetOrCreateWebViewEnvAsync()
|
||||
{
|
||||
if (_webViewEnv != null) return _webViewEnv;
|
||||
var userDataFolder = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LDKickWatch", "WebView2");
|
||||
Directory.CreateDirectory(userDataFolder);
|
||||
_webViewEnv = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
|
||||
return _webViewEnv;
|
||||
}
|
||||
|
||||
private void ViewModel_EmbeddedPlayRequested(object? sender, string channelName)
|
||||
{
|
||||
_ = Dispatcher.InvokeAsync(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_isWebViewInitialized)
|
||||
{
|
||||
var env = await GetOrCreateWebViewEnvAsync();
|
||||
await EmbeddedPlayer.EnsureCoreWebView2Async(env);
|
||||
EmbeddedPlayer.CoreWebView2.Settings.IsStatusBarEnabled = false;
|
||||
EmbeddedPlayer.CoreWebView2.Settings.AreDevToolsEnabled = false;
|
||||
|
||||
EmbeddedPlayer.CoreWebView2.ContainsFullScreenElementChanged += (_, _) =>
|
||||
{
|
||||
_viewModel.SetFullScreenState(EmbeddedPlayer.CoreWebView2.ContainsFullScreenElement);
|
||||
};
|
||||
|
||||
_isWebViewInitialized = true;
|
||||
}
|
||||
|
||||
EmbeddedPlayer.CoreWebView2.IsMuted = false;
|
||||
var playerUrl = $"https://player.kick.com/{channelName.ToLowerInvariant()}";
|
||||
EmbeddedPlayer.Source = new Uri(playerUrl);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_viewModel.StatusMessage = $"Dahili oynatıcı hatası: {ex.Message}";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ViewModel_EmbeddedVlcPlayRequested(object? sender, string streamUrl)
|
||||
{
|
||||
_ = Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_isWebViewInitialized)
|
||||
{
|
||||
EmbeddedPlayer.Source = new Uri("about:blank");
|
||||
}
|
||||
|
||||
VlcHost.UpdateLayout();
|
||||
var hwnd = VlcPanel.Handle;
|
||||
var vlcPath = _viewModel.Streamlink.FindPlayer("vlc", _viewModel.Config.PlayerPath);
|
||||
|
||||
if (vlcPath is null)
|
||||
{
|
||||
_viewModel.StatusMessage = "⚠ VLC bulunamadı! Lütfen VLC kurun veya Ayarlardan yolunu seçin.";
|
||||
return;
|
||||
}
|
||||
|
||||
var (success, msg) = _viewModel.Streamlink.PlayEmbeddedVlc(
|
||||
_viewModel.ActivePlayerChannel,
|
||||
hwnd,
|
||||
vlcPath,
|
||||
streamUrl,
|
||||
_viewModel.Config.ExtraStreamlinkArgs);
|
||||
|
||||
_viewModel.StatusMessage = msg;
|
||||
if (!success)
|
||||
{
|
||||
_viewModel.StopEmbeddedPlayer();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_viewModel.StatusMessage = $"Pencere içi VLC hatası: {ex.Message}";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ViewModel_EmbeddedStopRequested(object? sender, EventArgs e)
|
||||
{
|
||||
_ = Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_isWebViewInitialized)
|
||||
{
|
||||
EmbeddedPlayer.Source = new Uri("about:blank");
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private void ViewModel_EmbeddedMuteRequested(object? sender, bool isMuted)
|
||||
{
|
||||
_ = Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_isWebViewInitialized && EmbeddedPlayer.CoreWebView2 != null)
|
||||
{
|
||||
EmbeddedPlayer.CoreWebView2.IsMuted = isMuted;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private void ViewModel_EmbeddedReloadRequested(object? sender, EventArgs e)
|
||||
{
|
||||
_ = Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_isWebViewInitialized)
|
||||
{
|
||||
EmbeddedPlayer.Reload();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private void ViewModel_FullScreenChanged(object? sender, bool enable)
|
||||
{
|
||||
Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (enable)
|
||||
{
|
||||
_stateBeforeFullScreen = WindowState;
|
||||
WindowStyle = WindowStyle.None;
|
||||
ResizeMode = ResizeMode.NoResize;
|
||||
WindowState = WindowState.Normal;
|
||||
WindowState = WindowState.Maximized;
|
||||
}
|
||||
else
|
||||
{
|
||||
WindowStyle = WindowStyle.SingleBorderWindow;
|
||||
ResizeMode = ResizeMode.CanResize;
|
||||
WindowState = _stateBeforeFullScreen == WindowState.Minimized ? WindowState.Normal : _stateBeforeFullScreen;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void VlcPanel_DoubleClick(object? sender, EventArgs e)
|
||||
{
|
||||
_viewModel.ToggleFullScreenCommand.Execute(null);
|
||||
}
|
||||
|
||||
private void MainWindow_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.Escape && _viewModel.IsFullScreen)
|
||||
{
|
||||
_viewModel.SetFullScreenState(false);
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== MULTI-STREAM WEBVIEW2 HANDLERS ====================
|
||||
|
||||
private WebView2? GetMultiWebView(int index) => index switch
|
||||
{
|
||||
0 => MultiWebView0,
|
||||
1 => MultiWebView1,
|
||||
2 => MultiWebView2,
|
||||
3 => MultiWebView3,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private void ViewModel_MultiSlotPlayRequested(object? sender, MultiSlotPlayEventArgs e)
|
||||
{
|
||||
_ = Dispatcher.InvokeAsync(async () =>
|
||||
{
|
||||
var wv = GetMultiWebView(e.SlotIndex);
|
||||
if (wv is null) return;
|
||||
|
||||
try
|
||||
{
|
||||
if (!_isMultiWebViewInitialized[e.SlotIndex])
|
||||
{
|
||||
var env = await GetOrCreateWebViewEnvAsync();
|
||||
await wv.EnsureCoreWebView2Async(env);
|
||||
wv.CoreWebView2.Settings.IsStatusBarEnabled = false;
|
||||
wv.CoreWebView2.Settings.AreDevToolsEnabled = false;
|
||||
wv.CoreWebView2.ContainsFullScreenElementChanged += (_, _) =>
|
||||
{
|
||||
_viewModel.SetFullScreenState(wv.CoreWebView2.ContainsFullScreenElement);
|
||||
};
|
||||
_isMultiWebViewInitialized[e.SlotIndex] = true;
|
||||
}
|
||||
|
||||
wv.CoreWebView2.IsMuted = e.IsMuted;
|
||||
wv.Source = new Uri($"https://player.kick.com/{e.ChannelName.ToLowerInvariant()}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_viewModel.StatusMessage = $"Çoklu yayın #{e.SlotIndex + 1} hatası: {ex.Message}";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ViewModel_MultiSlotStopRequested(object? sender, int slotIndex)
|
||||
{
|
||||
_ = Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
var wv = GetMultiWebView(slotIndex);
|
||||
if (wv is null || !_isMultiWebViewInitialized[slotIndex]) return;
|
||||
try { wv.Source = new Uri("about:blank"); } catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private void ViewModel_MultiSlotMuteRequested(object? sender, MultiSlotPlayEventArgs e)
|
||||
{
|
||||
_ = Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
var wv = GetMultiWebView(e.SlotIndex);
|
||||
if (wv is null || !_isMultiWebViewInitialized[e.SlotIndex]) return;
|
||||
try
|
||||
{
|
||||
if (wv.CoreWebView2 != null)
|
||||
wv.CoreWebView2.IsMuted = e.IsMuted;
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== EMBEDDED CHAT AUTO-SCROLL ====================
|
||||
|
||||
private void EmbeddedChat_NewMessagesAppended(object? sender, EventArgs e)
|
||||
{
|
||||
if (_viewModel.EmbeddedChat.IsPaused) return;
|
||||
try
|
||||
{
|
||||
if (EmbeddedChatListBox.Items.Count > 0)
|
||||
{
|
||||
EmbeddedChatListBox.ScrollIntoView(EmbeddedChatListBox.Items[^1]);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(MainViewModel.ActivePage) && _viewModel.ActivePage == "exit")
|
||||
{
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
private void ChannelList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
if (e.OriginalSource is DependencyObject dep)
|
||||
{
|
||||
var current = dep;
|
||||
while (current != null && current is not System.Windows.Controls.ListBoxItem)
|
||||
{
|
||||
if (current is System.Windows.Controls.Primitives.ButtonBase)
|
||||
return;
|
||||
current = VisualTreeHelper.GetParent(current);
|
||||
}
|
||||
}
|
||||
|
||||
if (_viewModel.SelectedChannel is not null)
|
||||
{
|
||||
_viewModel.PlayChannelCommand.Execute(_viewModel.SelectedChannel.ChannelName);
|
||||
}
|
||||
}
|
||||
|
||||
private void RestoreWindowBounds()
|
||||
{
|
||||
var cfg = _viewModel.Config;
|
||||
if (cfg.WindowLeft >= 0 && cfg.WindowTop >= 0)
|
||||
{
|
||||
var isVisibleOnAnyScreen = System.Windows.Forms.Screen.AllScreens.Any(s =>
|
||||
s.WorkingArea.IntersectsWith(new System.Drawing.Rectangle(
|
||||
(int)cfg.WindowLeft, (int)cfg.WindowTop,
|
||||
(int)Math.Max(100, cfg.WindowWidth), (int)Math.Max(100, cfg.WindowHeight))));
|
||||
|
||||
if (isVisibleOnAnyScreen)
|
||||
{
|
||||
Left = cfg.WindowLeft;
|
||||
Top = cfg.WindowTop;
|
||||
}
|
||||
}
|
||||
if (cfg.WindowWidth >= MinWidth) Width = cfg.WindowWidth;
|
||||
if (cfg.WindowHeight >= MinHeight) Height = cfg.WindowHeight;
|
||||
|
||||
if (cfg.StartMinimized)
|
||||
{
|
||||
WindowState = WindowState.Minimized;
|
||||
if (cfg.MinimizeToTray)
|
||||
{
|
||||
Hide();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void MainWindow_StateChanged(object? sender, EventArgs e)
|
||||
{
|
||||
if (WindowState == WindowState.Minimized && _viewModel.Config.MinimizeToTray)
|
||||
Hide();
|
||||
}
|
||||
|
||||
public void RestoreAndBringToFront()
|
||||
{
|
||||
Show();
|
||||
if (WindowState == WindowState.Minimized)
|
||||
WindowState = WindowState.Normal;
|
||||
Activate();
|
||||
Topmost = true;
|
||||
Topmost = false;
|
||||
Focus();
|
||||
}
|
||||
|
||||
private void QualityButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is FrameworkElement fe && fe.ContextMenu != null)
|
||||
{
|
||||
foreach (var item in fe.ContextMenu.Items.OfType<System.Windows.Controls.MenuItem>())
|
||||
{
|
||||
var isCurrent = string.Equals(item.Tag as string, _viewModel.SelectedQuality, StringComparison.OrdinalIgnoreCase);
|
||||
var headerStr = item.Header?.ToString() ?? string.Empty;
|
||||
var clean = headerStr.Replace("✓", "", StringComparison.Ordinal).Trim();
|
||||
item.Header = isCurrent ? $"✓ {clean}" : $" {clean}";
|
||||
item.FontWeight = isCurrent ? FontWeights.Bold : FontWeights.Normal;
|
||||
}
|
||||
|
||||
fe.ContextMenu.PlacementTarget = fe;
|
||||
fe.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
|
||||
fe.ContextMenu.IsOpen = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void QualityMenuItem_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is System.Windows.Controls.MenuItem mi && mi.Tag is string q)
|
||||
{
|
||||
_viewModel.SetStreamQuality(q);
|
||||
}
|
||||
}
|
||||
|
||||
private void MainWindow_Closing(object? sender, CancelEventArgs e)
|
||||
{
|
||||
// Pencere kapatıldığında (X veya Alt+F4) uygulama arkaplanda açık kalmaz,
|
||||
// tüm oynatıcı/WebView2/sohbet süreçlerini temizleyip tamamen kapanır.
|
||||
var bounds = WindowState == WindowState.Normal ? new Rect(Left, Top, Width, Height) : RestoreBounds;
|
||||
if (!bounds.IsEmpty && bounds.Width > 0 && bounds.Height > 0)
|
||||
{
|
||||
_viewModel.Config.WindowLeft = bounds.Left;
|
||||
_viewModel.Config.WindowTop = bounds.Top;
|
||||
_viewModel.Config.WindowWidth = bounds.Width;
|
||||
_viewModel.Config.WindowHeight = bounds.Height;
|
||||
}
|
||||
|
||||
_viewModel.Stop();
|
||||
_notifications.Dispose();
|
||||
|
||||
try { EmbeddedPlayer.Dispose(); } catch { }
|
||||
try { MultiWebView0.Dispose(); } catch { }
|
||||
try { MultiWebView1.Dispose(); } catch { }
|
||||
try { MultiWebView2.Dispose(); } catch { }
|
||||
try { MultiWebView3.Dispose(); } catch { }
|
||||
try { VlcHost.Dispose(); } catch { }
|
||||
|
||||
// Tüm arkaplan iş parçacıkları ve süreçleriyle birlikte hemen ve tamamen sonlandır
|
||||
Environment.Exit(0);
|
||||
}
|
||||
|
||||
private void BrowseStreamlink_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Filter = "Streamlink|streamlink.exe|Tüm Dosyalar|*.*",
|
||||
Title = "Streamlink Yolunu Seçin"
|
||||
};
|
||||
if (dlg.ShowDialog() == true)
|
||||
{
|
||||
_viewModel.Config.StreamlinkPath = dlg.FileName;
|
||||
}
|
||||
}
|
||||
|
||||
private void BrowsePlayer_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Filter = "Oynatıcı Yürütülebilir Dosyası|*.exe|Tüm Dosyalar|*.*",
|
||||
Title = "Oynatıcı (VLC/MPV) Yolunu Seçin"
|
||||
};
|
||||
if (dlg.ShowDialog() == true)
|
||||
{
|
||||
_viewModel.Config.PlayerPath = dlg.FileName;
|
||||
}
|
||||
}
|
||||
|
||||
private void BrowseSound_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Filter = "WAV Ses Dosyası|*.wav|Tüm Dosyalar|*.*",
|
||||
Title = "Bildirim Ses Dosyasını (.wav) Seçin"
|
||||
};
|
||||
if (dlg.ShowDialog() == true)
|
||||
{
|
||||
_viewModel.Config.CustomSoundPath = dlg.FileName;
|
||||
}
|
||||
}
|
||||
|
||||
private void ExportFavorites_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new SaveFileDialog
|
||||
{
|
||||
Filter = "JSON Yedek Dosyası (*.json)|*.json|CSV Tablo Dosyası (*.csv)|*.csv",
|
||||
FileName = $"LDKickWatch_Favoriler_{DateTime.Now:yyyyMMdd}.json",
|
||||
Title = "Favori Kanalları Dışa Aktar"
|
||||
};
|
||||
if (dlg.ShowDialog() == true)
|
||||
{
|
||||
_viewModel.ExportFavoritesToFile(dlg.FileName);
|
||||
}
|
||||
}
|
||||
|
||||
private void ImportFavorites_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Filter = "Desteklenen Dosyalar (*.json;*.csv)|*.json;*.csv|JSON (*.json)|*.json|CSV (*.csv)|*.csv",
|
||||
Title = "Favori Kanalları İçe Aktar"
|
||||
};
|
||||
if (dlg.ShowDialog() == true)
|
||||
{
|
||||
_viewModel.ImportFavoritesFromFile(dlg.FileName);
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveSettings_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
_viewModel.SaveConfig();
|
||||
_viewModel.StatusMessage = "✔ Ayarlar kaydedildi ve uygulandı.";
|
||||
_viewModel.ActivePage = "home";
|
||||
}
|
||||
|
||||
private void CreateDesktopShortcut_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ShortcutService.CreateDesktopShortcut(out string message))
|
||||
{
|
||||
_viewModel.StatusMessage = $"✔ {message}";
|
||||
System.Windows.MessageBox.Show(message, "Masaüstü Kısayolu", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
else
|
||||
{
|
||||
_viewModel.StatusMessage = $"⚠ {message}";
|
||||
System.Windows.MessageBox.Show(message, "Hata", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
private class RelayFocusCommand : ICommand
|
||||
{
|
||||
private readonly MainWindow _win;
|
||||
public RelayFocusCommand(MainWindow win) => _win = win;
|
||||
public bool CanExecute(object? parameter) => true;
|
||||
public void Execute(object? parameter)
|
||||
{
|
||||
_win._viewModel.ActivePage = "home";
|
||||
if (_win.FindName("SearchBox") is System.Windows.Controls.TextBox tb)
|
||||
{
|
||||
tb.Focus();
|
||||
tb.SelectAll();
|
||||
}
|
||||
}
|
||||
public event EventHandler? CanExecuteChanged { add { } remove { } }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
<Window x:Class="KickStreamHub.Views.PlayerWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
|
||||
xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
|
||||
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
|
||||
Title="LD KickWatch — Canlı Yayın Oynatıcı" Height="720" Width="1140" MinWidth="480" MinHeight="340"
|
||||
Icon="pack://application:,,,/Resources/app.ico"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
KeyDown="PlayerWindow_KeyDown"
|
||||
Background="#04090F">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Control Bar (Collapsed in Fullscreen) -->
|
||||
<Border x:Name="TopBar" Grid.Row="0" Background="#0D141F" Padding="12,7" BorderBrush="#1C283B" BorderThickness="0,0,0,1">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Left: Channel Title, Engine Switcher (Web vs VLC) and Quality Selector -->
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<Ellipse Width="8" Height="8" Fill="#53FC18" Margin="0,0,8,0" VerticalAlignment="Center" />
|
||||
<TextBlock x:Name="ChannelTitleText" FontWeight="ExtraBold" FontSize="13.5" Foreground="#F8FAFC" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
|
||||
<!-- Web Engine Button -->
|
||||
<Button x:Name="WebEngineBtn" Content="🌐 Web" FontSize="11" Padding="8,3.5" Margin="0,0,4,0"
|
||||
Style="{StaticResource SecondaryButton}"
|
||||
Click="WebEngineBtn_Click"
|
||||
ToolTip="Dahili WebView2 Oynatıcıya Geç" />
|
||||
|
||||
<!-- VLC Engine Button -->
|
||||
<Button x:Name="VlcEngineBtn" Content="🎬 VLC" FontSize="11" Padding="8,3.5" Margin="0,0,8,0"
|
||||
Style="{StaticResource SecondaryButton}"
|
||||
Click="VlcEngineBtn_Click"
|
||||
ToolTip="Pencere İçi Gömülü VLC Oynatıcıya Geç (Düşük Gecikme & Düşük Kaynak)" />
|
||||
|
||||
<!-- Quality Selector Button with ContextMenu -->
|
||||
<Button x:Name="QualityButton" Style="{StaticResource SecondaryButton}"
|
||||
Padding="10,4.5"
|
||||
Margin="0,0,10,0"
|
||||
VerticalAlignment="Center"
|
||||
Click="QualityButton_Click"
|
||||
ToolTip="Yayın Çözünürlüğü ve Kalitesini Değiştir">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock Text="⚙ " Foreground="#53FC18" FontSize="11" VerticalAlignment="Center" />
|
||||
<TextBlock x:Name="QualityDisplayText" Text="Kaynak (En İyi)"
|
||||
FontSize="11.5" FontWeight="Bold" Foreground="#F8FAFC" VerticalAlignment="Center" Margin="0,0,6,0" />
|
||||
<TextBlock Text="▾" FontSize="11" Foreground="#94A3B8" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<Button.ContextMenu>
|
||||
<ContextMenu x:Name="QualityContextMenu">
|
||||
<MenuItem Header="Kaynak (En İyi)" Tag="best" Click="QualityMenuItem_Click" />
|
||||
<MenuItem Header="1080p 60 FPS" Tag="1080p60" Click="QualityMenuItem_Click" />
|
||||
<MenuItem Header="720p 60 FPS" Tag="720p60" Click="QualityMenuItem_Click" />
|
||||
<MenuItem Header="720p (Normal)" Tag="720p" Click="QualityMenuItem_Click" />
|
||||
<MenuItem Header="480p" Tag="480p" Click="QualityMenuItem_Click" />
|
||||
<MenuItem Header="360p (Tasarruf)" Tag="360p" Click="QualityMenuItem_Click" />
|
||||
<MenuItem Header="160p (Düşük)" Tag="160p" Click="QualityMenuItem_Click" />
|
||||
<MenuItem Header="En Düşük (worst)" Tag="worst" Click="QualityMenuItem_Click" />
|
||||
<MenuItem Header="Sadece Ses" Tag="audio_only" Click="QualityMenuItem_Click" />
|
||||
</ContextMenu>
|
||||
</Button.ContextMenu>
|
||||
</Button>
|
||||
|
||||
<TextBlock x:Name="StatusSubText" Text="• F11 veya Çift Tıklama ile Tam Ekran" FontSize="11" Foreground="#64748B" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Right: Controls -->
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<CheckBox x:Name="TopMostCheck" Content="📌 Üstte Tut (PiP)" FontSize="11.5" Margin="0,0,12,0"
|
||||
VerticalAlignment="Center" Checked="TopMostCheck_Changed" Unchecked="TopMostCheck_Changed" />
|
||||
<Button x:Name="MuteBtn" Content="🔊 Sesi Kapat" Style="{StaticResource SecondaryButton}"
|
||||
FontSize="11" Padding="9,4" Margin="0,0,6,0" Click="MuteBtn_Click" />
|
||||
<Button Content="⟳ Yenile" Style="{StaticResource SecondaryButton}"
|
||||
FontSize="11" Padding="9,4" Margin="0,0,6,0" Click="ReloadBtn_Click" />
|
||||
<Button Content="⛶ Tam Ekran (F11)" Style="{StaticResource PrimaryButton}"
|
||||
FontSize="11" Padding="10,4" Click="FullScreenBtn_Click" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Dual Player Surface (WebView2 + WindowsFormsHost VLC) -->
|
||||
<Grid Grid.Row="1" Background="#04090F">
|
||||
<wv2:WebView2 x:Name="WebView" DefaultBackgroundColor="#04090F" />
|
||||
|
||||
<wfi:WindowsFormsHost x:Name="VlcHost"
|
||||
Background="#04090F"
|
||||
Visibility="Collapsed">
|
||||
<wf:Panel x:Name="VlcPanel" Dock="Fill" DoubleClick="VlcPanel_DoubleClick" />
|
||||
</wfi:WindowsFormsHost>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
|
@ -1,351 +0,0 @@
|
|||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using KickStreamHub.Helpers;
|
||||
using KickStreamHub.Services;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace KickStreamHub.Views;
|
||||
|
||||
public partial class PlayerWindow : Window
|
||||
{
|
||||
private readonly string _channelName;
|
||||
private readonly KickApiService _api = new();
|
||||
private readonly StreamlinkService _streamlink = new();
|
||||
private Process? _vlcProcess;
|
||||
private bool _isVlcActive;
|
||||
private bool _isFullScreen;
|
||||
private WindowState _previousState = WindowState.Normal;
|
||||
private string _currentQuality = "best";
|
||||
private string _cachedPlaybackUrl = string.Empty;
|
||||
|
||||
private static readonly SolidColorBrush WebActiveBg = new((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#1A3822"));
|
||||
private static readonly SolidColorBrush WebActiveFg = new((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#53FC18"));
|
||||
private static readonly SolidColorBrush VlcActiveBg = new((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#2A2410"));
|
||||
private static readonly SolidColorBrush VlcActiveFg = new((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#F59E0B"));
|
||||
private static readonly SolidColorBrush PassiveBg = new((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#141D2B"));
|
||||
private static readonly SolidColorBrush PassiveFg = new((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#F8FAFC"));
|
||||
private static readonly SolidColorBrush PassiveBorder = new((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#1E2D42"));
|
||||
|
||||
public PlayerWindow(string channelName)
|
||||
{
|
||||
InitializeComponent();
|
||||
_channelName = channelName;
|
||||
Title = $"{channelName.ToUpperInvariant()} — Canlı Yayın (LD KickWatch)";
|
||||
ChannelTitleText.Text = channelName.ToUpperInvariant();
|
||||
UpdateEngineButtons();
|
||||
Loaded += PlayerWindow_Loaded;
|
||||
}
|
||||
|
||||
private async void PlayerWindow_Loaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
var userDataFolder = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LDKickWatch", "WebView2");
|
||||
Directory.CreateDirectory(userDataFolder);
|
||||
|
||||
var env = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
|
||||
await WebView.EnsureCoreWebView2Async(env);
|
||||
|
||||
WebView.CoreWebView2.Settings.IsStatusBarEnabled = false;
|
||||
WebView.CoreWebView2.Settings.AreDevToolsEnabled = false;
|
||||
|
||||
// HTML5 Video Tam Ekran (requestFullscreen) olayını yakala
|
||||
WebView.CoreWebView2.ContainsFullScreenElementChanged += (_, _) =>
|
||||
{
|
||||
SetFullScreen(WebView.CoreWebView2.ContainsFullScreenElement);
|
||||
};
|
||||
|
||||
var playerUrl = $"https://player.kick.com/{_channelName.ToLowerInvariant()}";
|
||||
WebView.Source = new Uri(playerUrl);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Windows.MessageBox.Show($"Oynatıcı başlatılamadı: {ex.Message}", "Hata", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateEngineButtons()
|
||||
{
|
||||
if (_isVlcActive)
|
||||
{
|
||||
VlcEngineBtn.Background = VlcActiveBg;
|
||||
VlcEngineBtn.Foreground = VlcActiveFg;
|
||||
VlcEngineBtn.BorderBrush = VlcActiveFg;
|
||||
VlcEngineBtn.FontWeight = FontWeights.Bold;
|
||||
|
||||
WebEngineBtn.Background = PassiveBg;
|
||||
WebEngineBtn.Foreground = PassiveFg;
|
||||
WebEngineBtn.BorderBrush = PassiveBorder;
|
||||
WebEngineBtn.FontWeight = FontWeights.Normal;
|
||||
|
||||
VlcHost.Visibility = Visibility.Visible;
|
||||
WebView.Visibility = Visibility.Collapsed;
|
||||
MuteBtn.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
else
|
||||
{
|
||||
WebEngineBtn.Background = WebActiveBg;
|
||||
WebEngineBtn.Foreground = WebActiveFg;
|
||||
WebEngineBtn.BorderBrush = WebActiveFg;
|
||||
WebEngineBtn.FontWeight = FontWeights.Bold;
|
||||
|
||||
VlcEngineBtn.Background = PassiveBg;
|
||||
VlcEngineBtn.Foreground = PassiveFg;
|
||||
VlcEngineBtn.BorderBrush = PassiveBorder;
|
||||
VlcEngineBtn.FontWeight = FontWeights.Normal;
|
||||
|
||||
WebView.Visibility = Visibility.Visible;
|
||||
VlcHost.Visibility = Visibility.Collapsed;
|
||||
MuteBtn.Visibility = Visibility.Visible;
|
||||
}
|
||||
}
|
||||
|
||||
private void WebEngineBtn_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (!_isVlcActive) return;
|
||||
_isVlcActive = false;
|
||||
StopVlc();
|
||||
UpdateEngineButtons();
|
||||
|
||||
try
|
||||
{
|
||||
var playerUrl = $"https://player.kick.com/{_channelName.ToLowerInvariant()}";
|
||||
WebView.Source = new Uri(playerUrl);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private async void VlcEngineBtn_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_isVlcActive) return;
|
||||
await StartVlcAsync();
|
||||
}
|
||||
|
||||
private async Task StartVlcAsync()
|
||||
{
|
||||
var vlcPath = _streamlink.FindPlayer("vlc", null);
|
||||
if (vlcPath is null)
|
||||
{
|
||||
System.Windows.MessageBox.Show(
|
||||
"VLC Media Player bulunamadı! Lütfen bilgisayarınıza VLC kurun.",
|
||||
"VLC Bulunamadı",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Warning);
|
||||
return;
|
||||
}
|
||||
|
||||
StatusSubText.Text = "⏳ VLC yayını hazırlanıyor...";
|
||||
_isVlcActive = true;
|
||||
UpdateEngineButtons();
|
||||
|
||||
try
|
||||
{
|
||||
if (WebView.CoreWebView2 != null)
|
||||
{
|
||||
WebView.Source = new Uri("about:blank");
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(_cachedPlaybackUrl))
|
||||
{
|
||||
var channelData = await _api.GetChannelAsync(_channelName).ConfigureAwait(true);
|
||||
if (channelData?.Livestream is null || string.IsNullOrWhiteSpace(channelData.PlaybackUrl))
|
||||
{
|
||||
StatusSubText.Text = "🔴 Kanal şu anda canlı yayında değil.";
|
||||
System.Windows.MessageBox.Show(
|
||||
$"{_channelName.ToUpperInvariant()} kanalı şu anda canlı yayında değil veya akış linki alınamadı.",
|
||||
"Yayın Kapalı",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Information);
|
||||
WebEngineBtn_Click(this, new RoutedEventArgs());
|
||||
return;
|
||||
}
|
||||
_cachedPlaybackUrl = channelData.PlaybackUrl;
|
||||
}
|
||||
|
||||
var streamUrl = await _api.ResolveQualityUrlAsync(_cachedPlaybackUrl, _currentQuality).ConfigureAwait(true);
|
||||
|
||||
VlcHost.UpdateLayout();
|
||||
var hwnd = VlcPanel.Handle;
|
||||
|
||||
StopVlc();
|
||||
|
||||
var args = $"\"{streamUrl}\" -I dummy --dummy-quiet --drawable-hwnd={hwnd.ToInt64()} --no-video-title-show --network-caching=800 --clock-jitter=0 --no-sub-autodetect-file";
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = vlcPath,
|
||||
Arguments = args,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
WindowStyle = ProcessWindowStyle.Hidden,
|
||||
};
|
||||
|
||||
var proc = Process.Start(psi);
|
||||
if (proc is null)
|
||||
{
|
||||
StatusSubText.Text = "⚠ VLC işlemi başlatılamadı.";
|
||||
return;
|
||||
}
|
||||
|
||||
ChildProcessTracker.AddProcess(proc);
|
||||
proc.EnableRaisingEvents = true;
|
||||
proc.Exited += (_, _) =>
|
||||
{
|
||||
_ = Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (ReferenceEquals(_vlcProcess, proc))
|
||||
{
|
||||
_vlcProcess = null;
|
||||
if (_isVlcActive)
|
||||
{
|
||||
StatusSubText.Text = "⏹ VLC yayını sonlandı.";
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_vlcProcess = proc;
|
||||
StatusSubText.Text = $"🎬 VLC aktif ({_currentQuality}) • F11 Tam Ekran";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusSubText.Text = $"VLC Hatası: {ex.Message}";
|
||||
LoggingService.Instance.Error($"PlayerWindow VLC başlatılamadı ({_channelName})", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void StopVlc()
|
||||
{
|
||||
if (_vlcProcess != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_vlcProcess.HasExited)
|
||||
_vlcProcess.Kill(true);
|
||||
}
|
||||
catch { }
|
||||
_vlcProcess = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void QualityButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (QualityButton.ContextMenu != null)
|
||||
{
|
||||
foreach (var item in QualityButton.ContextMenu.Items)
|
||||
{
|
||||
if (item is MenuItem mi && mi.Tag is string tag)
|
||||
{
|
||||
mi.IsChecked = string.Equals(tag, _currentQuality, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
QualityButton.ContextMenu.PlacementTarget = QualityButton;
|
||||
QualityButton.ContextMenu.IsOpen = true;
|
||||
}
|
||||
}
|
||||
|
||||
private async void QualityMenuItem_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is MenuItem mi && mi.Tag is string newQuality)
|
||||
{
|
||||
_currentQuality = newQuality;
|
||||
QualityDisplayText.Text = mi.Header?.ToString() ?? newQuality;
|
||||
|
||||
if (_isVlcActive)
|
||||
{
|
||||
await StartVlcAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void VlcPanel_DoubleClick(object? sender, EventArgs e)
|
||||
{
|
||||
Dispatcher.BeginInvoke(() => SetFullScreen(!_isFullScreen));
|
||||
}
|
||||
|
||||
private void SetFullScreen(bool enable)
|
||||
{
|
||||
if (_isFullScreen == enable) return;
|
||||
_isFullScreen = enable;
|
||||
|
||||
if (enable)
|
||||
{
|
||||
_previousState = WindowState;
|
||||
TopBar.Visibility = Visibility.Collapsed;
|
||||
WindowStyle = WindowStyle.None;
|
||||
ResizeMode = ResizeMode.NoResize;
|
||||
WindowState = WindowState.Normal;
|
||||
WindowState = WindowState.Maximized;
|
||||
}
|
||||
else
|
||||
{
|
||||
TopBar.Visibility = Visibility.Visible;
|
||||
WindowStyle = WindowStyle.SingleBorderWindow;
|
||||
ResizeMode = ResizeMode.CanResize;
|
||||
WindowState = _previousState == WindowState.Minimized ? WindowState.Normal : _previousState;
|
||||
}
|
||||
}
|
||||
|
||||
private void FullScreenBtn_Click(object sender, RoutedEventArgs e) => SetFullScreen(!_isFullScreen);
|
||||
|
||||
private async void ReloadBtn_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_isVlcActive)
|
||||
{
|
||||
_cachedPlaybackUrl = string.Empty;
|
||||
await StartVlcAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
try { WebView.Reload(); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private void MuteBtn_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (WebView.CoreWebView2 != null)
|
||||
{
|
||||
WebView.CoreWebView2.IsMuted = !WebView.CoreWebView2.IsMuted;
|
||||
MuteBtn.Content = WebView.CoreWebView2.IsMuted ? "🔇 Sesi Aç" : "🔊 Sesi Kapat";
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void TopMostCheck_Changed(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Topmost = TopMostCheck.IsChecked == true;
|
||||
}
|
||||
|
||||
private void PlayerWindow_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.F11)
|
||||
{
|
||||
SetFullScreen(!_isFullScreen);
|
||||
e.Handled = true;
|
||||
}
|
||||
else if (e.Key == Key.Escape && _isFullScreen)
|
||||
{
|
||||
SetFullScreen(false);
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnClosed(EventArgs e)
|
||||
{
|
||||
StopVlc();
|
||||
try { WebView.Dispose(); } catch { }
|
||||
base.OnClosed(e);
|
||||
}
|
||||
}
|
||||
129
src/components/AboutView.tsx
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import React from 'react';
|
||||
import {
|
||||
ShieldCheck,
|
||||
Cpu,
|
||||
Zap,
|
||||
Globe,
|
||||
Github,
|
||||
Radio,
|
||||
} from 'lucide-react';
|
||||
import { open } from '@tauri-apps/plugin-shell';
|
||||
|
||||
export const AboutView: React.FC = () => {
|
||||
const handleOpenLink = (url: string) => {
|
||||
open(url).catch(() => {
|
||||
window.open(url, '_blank');
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center p-6 bg-[#101318] overflow-y-auto select-none custom-scrollbar">
|
||||
<div className="w-full max-w-xl bg-[#151921] border border-[#2E3542]/70 rounded-3xl p-8 shadow-2xl relative overflow-hidden">
|
||||
{/* Glow backdrop */}
|
||||
<div className="absolute -top-24 -right-24 w-60 h-60 bg-[#60E0B1]/10 rounded-full blur-3xl pointer-events-none" />
|
||||
<div className="absolute -bottom-24 -left-24 w-60 h-60 bg-[#247553]/15 rounded-full blur-3xl pointer-events-none" />
|
||||
|
||||
{/* Brand Header */}
|
||||
<div className="flex flex-col items-center text-center mb-6">
|
||||
<div className="relative mb-3">
|
||||
<img
|
||||
src="/logo.png"
|
||||
alt="LD KickWatch Logo"
|
||||
className="w-20 h-20 rounded-2xl object-contain bg-[#101318] drop-shadow-[0_0_25px_rgba(96,224,177,0.4)] border border-[#2E3542]"
|
||||
/>
|
||||
<span className="absolute -bottom-1 -right-1 px-2 py-0.5 rounded-full bg-[#247553] text-[#60E0B1] text-[10px] font-bold border border-[#60E0B1]/40">
|
||||
v2.6.12
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<h1 className="text-xl font-extrabold text-slate-100 tracking-wider">
|
||||
LD <span className="text-[#60E0B1]">KICKWATCH</span>
|
||||
</h1>
|
||||
<p className="text-xs text-slate-400 mt-1 max-w-sm">
|
||||
Kick.com için Yeni Nesil Masaüstü Canlı Yayın & Sohbet Stüdyosu
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Feature Grid */}
|
||||
<div className="grid grid-cols-2 gap-3 mb-6">
|
||||
<div className="p-3 rounded-2xl bg-[#1B202A]/70 border border-[#2E3542]/50 flex items-start gap-2.5">
|
||||
<Cpu className="w-4 h-4 text-[#60E0B1] shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h4 className="text-xs font-semibold text-slate-200">
|
||||
Tauri v2 + Rust
|
||||
</h4>
|
||||
<p className="text-[11px] text-slate-400 mt-0.5 leading-tight">
|
||||
Sıfır bellek sızıntısı, ultra düşük CPU tüketimi ve anında tepki.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-3 rounded-2xl bg-[#1B202A]/70 border border-[#2E3542]/50 flex items-start gap-2.5">
|
||||
<Zap className="w-4 h-4 text-[#60E0B1] shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h4 className="text-xs font-semibold text-slate-200">
|
||||
Pusher Canlı Sohbet
|
||||
</h4>
|
||||
<p className="text-[11px] text-slate-400 mt-0.5 leading-tight">
|
||||
Kick WebSocket altyapısı ile anlık mesajlaşma ve Kick ifadeleri.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-3 rounded-2xl bg-[#1B202A]/70 border border-[#2E3542]/50 flex items-start gap-2.5">
|
||||
<Radio className="w-4 h-4 text-[#60E0B1] shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h4 className="text-xs font-semibold text-slate-200">
|
||||
2x2 Çoklu İzleme
|
||||
</h4>
|
||||
<p className="text-[11px] text-slate-400 mt-0.5 leading-tight">
|
||||
Aynı anda 4 yayını izleme ve tek tıkla ses odaklama yeteneği.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-3 rounded-2xl bg-[#1B202A]/70 border border-[#2E3542]/50 flex items-start gap-2.5">
|
||||
<ShieldCheck className="w-4 h-4 text-[#60E0B1] shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h4 className="text-xs font-semibold text-slate-200">
|
||||
Harici Oynatıcılar
|
||||
</h4>
|
||||
<p className="text-[11px] text-slate-400 mt-0.5 leading-tight">
|
||||
VLC, MPV ve Streamlink ile sıfır gecikmeli native izleme desteği.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer Credit & Signature */}
|
||||
<div className="pt-4 border-t border-[#2E3542]/50 flex items-center justify-between text-xs text-slate-400">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span>Geliştirici:</span>
|
||||
<span className="font-bold text-slate-200 hover:text-[#60E0B1] transition-colors">
|
||||
LilDosto
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOpenLink('https://kick.com')}
|
||||
className="p-1.5 rounded-lg bg-[#1B202A] text-slate-400 hover:text-white hover:bg-[#247553]/40 transition-colors"
|
||||
title="Kick.com Resmi Sitesi"
|
||||
>
|
||||
<Globe className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOpenLink('https://github.com/LilDosto/LD-KickWatch')}
|
||||
className="p-1.5 rounded-lg bg-[#1B202A] text-slate-400 hover:text-white hover:bg-[#247553]/40 transition-colors"
|
||||
title="GitHub Kaynak Kodu"
|
||||
>
|
||||
<Github className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
238
src/components/ChannelCard.tsx
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
import React, { useState } from 'react';
|
||||
import {
|
||||
Play,
|
||||
ExternalLink,
|
||||
Users,
|
||||
CheckCircle2,
|
||||
Trash2,
|
||||
Tag,
|
||||
Radio,
|
||||
Clock,
|
||||
} from 'lucide-react';
|
||||
import { useAppStore } from '../store/appStore';
|
||||
import { computeUptimeSeconds, formatUptimeCompact, useNowTick } from '../lib/time';
|
||||
import type { ChannelCard as ChannelCardType } from '../types';
|
||||
|
||||
interface ChannelCardProps {
|
||||
channel: ChannelCardType;
|
||||
onEditGroup: (channel: ChannelCardType) => void;
|
||||
}
|
||||
|
||||
export const ChannelCard: React.FC<ChannelCardProps> = ({ channel, onEditGroup }) => {
|
||||
const playChannel = useAppStore((s) => s.playChannel);
|
||||
const removeChannel = useAppStore((s) => s.removeChannel);
|
||||
const activeStream = useAppStore((s) => s.activeStream);
|
||||
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const isCurrentlyPlaying =
|
||||
activeStream?.channel_name.toLowerCase() === channel.channel_name.toLowerCase();
|
||||
const nowMs = useNowTick(channel.is_live && !!channel.started_at, 30000);
|
||||
const uptimeSecs = channel.is_live
|
||||
? computeUptimeSeconds(channel.started_at, undefined, nowMs)
|
||||
: 0;
|
||||
|
||||
const handleCardClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
playChannel(channel);
|
||||
};
|
||||
|
||||
const handlePlayInternal = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
playChannel(channel, false);
|
||||
};
|
||||
|
||||
const handlePlayExternal = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
playChannel(channel, true);
|
||||
};
|
||||
|
||||
const handleRemove = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (confirm(`"${channel.channel_name}" kanalını favorilerinizden kaldırmak istediğinize emin misiniz?`)) {
|
||||
removeChannel(channel.channel_name);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
onClick={handleCardClick}
|
||||
className={`group relative flex flex-col justify-between p-4 rounded-2xl cursor-pointer transition-all duration-300 border backdrop-blur-md select-none overflow-hidden ${
|
||||
isCurrentlyPlaying
|
||||
? 'bg-[#151921] border-[#60E0B1]/60 shadow-[0_0_20px_rgba(96,224,177,0.25)]'
|
||||
: channel.is_live
|
||||
? 'bg-[#151921]/90 hover:bg-[#1B202A] border-[#2E3542]/70 hover:border-[#60E0B1]/40 hover:shadow-[0_4px_25px_rgba(0,0,0,0.5)]'
|
||||
: 'bg-[#13161C]/80 hover:bg-[#181D26] border-[#242A35]/60 hover:border-[#2E3542] opacity-80 hover:opacity-100'
|
||||
}`}
|
||||
>
|
||||
{/* Top Row: Avatar, Name, Badges */}
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Avatar with Live Indicator Ring */}
|
||||
<div className="relative shrink-0">
|
||||
<div
|
||||
className={`w-12 h-12 rounded-xl overflow-hidden bg-[#1B202A] flex items-center justify-center border ${
|
||||
channel.is_live
|
||||
? 'border-[#60E0B1] ring-2 ring-[#60E0B1]/30 shadow-md'
|
||||
: 'border-[#2E3542]'
|
||||
}`}
|
||||
>
|
||||
{channel.avatar_url ? (
|
||||
<img
|
||||
src={channel.avatar_url}
|
||||
alt={channel.channel_name}
|
||||
className="w-full h-full object-cover"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLElement).style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span className="text-base font-bold text-slate-300 uppercase">
|
||||
{channel.channel_name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{channel.is_live && (
|
||||
<span className="absolute -bottom-1 -right-1 flex h-3.5 w-3.5">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-[#60E0B1] opacity-75" />
|
||||
<span className="relative inline-flex rounded-full h-3.5 w-3.5 bg-[#4CE0AC] border-2 border-[#101318]" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Channel Details */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<h3 className="text-sm font-semibold text-slate-100 truncate group-hover:text-[#60E0B1] transition-colors">
|
||||
{channel.channel_name}
|
||||
</h3>
|
||||
{channel.verified && (
|
||||
<span title="Doğrulanmış Kanal">
|
||||
<CheckCircle2 className="w-3.5 h-3.5 text-[#60E0B1] shrink-0" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Group and Category */}
|
||||
<div className="flex items-center gap-2 mt-1 flex-wrap">
|
||||
{channel.is_live ? (
|
||||
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-bold bg-[#247553]/40 text-[#60E0B1] border border-[#247553]/60">
|
||||
<Radio className="w-2.5 h-2.5" />
|
||||
CANLI
|
||||
</span>
|
||||
) : (
|
||||
<span className="px-1.5 py-0.5 rounded text-[10px] font-medium bg-[#1B202A] text-slate-400 border border-[#2E3542]/50">
|
||||
ÇEVRİMDIŞI
|
||||
</span>
|
||||
)}
|
||||
|
||||
{channel.category && (
|
||||
<span
|
||||
className="px-1.5 py-0.5 rounded text-[10px] font-medium bg-[#1B202A] text-slate-300 border border-[#2E3542]/50 truncate max-w-[120px]"
|
||||
title={channel.category}
|
||||
>
|
||||
{channel.category}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{channel.group_name && (
|
||||
<span className="px-1.5 py-0.5 rounded text-[10px] font-medium bg-[#1E2633] text-emerald-300 border border-emerald-500/30">
|
||||
{channel.group_name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stream Title */}
|
||||
<div className="mt-3 min-h-[36px]">
|
||||
{channel.is_live && channel.title ? (
|
||||
<p
|
||||
className="text-xs text-slate-300 line-clamp-2 leading-relaxed"
|
||||
title={channel.title}
|
||||
>
|
||||
{channel.title}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-slate-500 italic">
|
||||
Yayın kapalı veya başlık bilgisi yok
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer: Viewers Count & Action Buttons */}
|
||||
<div className="mt-3 pt-2.5 border-t border-[#2E3542]/40 flex items-center justify-between gap-2 flex-wrap">
|
||||
<div className="flex items-center gap-1.5 text-xs text-slate-400 shrink-0">
|
||||
{channel.is_live ? (
|
||||
<>
|
||||
<Users className="w-3.5 h-3.5 text-[#60E0B1]" />
|
||||
<span className="font-semibold text-slate-200">
|
||||
{channel.viewers.toLocaleString()}
|
||||
</span>
|
||||
<span className="hidden xl:inline text-[11px] text-slate-400">izleyici</span>
|
||||
{uptimeSecs > 0 && (
|
||||
<span
|
||||
title="Canlı yayın süresi"
|
||||
className="inline-flex items-center gap-1 text-[11px] font-medium text-slate-300 ml-1"
|
||||
>
|
||||
<span>·</span>
|
||||
<Clock className="w-3 h-3 text-[#60E0B1]" />
|
||||
<span>{formatUptimeCompact(uptimeSecs)}</span>
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-[11px] text-slate-500">Beklemede</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div
|
||||
className={`flex items-center gap-0.5 flex-wrap justify-end transition-opacity duration-200 ${
|
||||
isHovered ? 'opacity-100' : 'opacity-70'
|
||||
}`}
|
||||
>
|
||||
{/* Group edit */}
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onEditGroup(channel);
|
||||
}}
|
||||
title="Grup Düzenle"
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-100 hover:bg-[#1B202A] transition-colors shrink-0"
|
||||
>
|
||||
<Tag className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
{/* External player */}
|
||||
<button
|
||||
onClick={handlePlayExternal}
|
||||
title="Harici Oynatıcıda Aç (VLC/MPV)"
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-[#60E0B1] hover:bg-[#1B202A] transition-colors shrink-0"
|
||||
>
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
{/* Play in-app */}
|
||||
<button
|
||||
onClick={handlePlayInternal}
|
||||
title="Uygulama İçi İzle"
|
||||
className="p-1.5 rounded-lg bg-[#247553]/60 text-[#60E0B1] hover:bg-[#247553] hover:text-white transition-colors"
|
||||
>
|
||||
<Play className="w-3.5 h-3.5 fill-current" />
|
||||
</button>
|
||||
|
||||
{/* Delete */}
|
||||
<button
|
||||
onClick={handleRemove}
|
||||
title="Kanalı Kaldır"
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-[#1B202A] transition-colors"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
380
src/components/ChannelList.tsx
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
import React, { useMemo, useState } from 'react';
|
||||
import {
|
||||
Search,
|
||||
RefreshCw,
|
||||
Users,
|
||||
Play,
|
||||
ExternalLink,
|
||||
Plus,
|
||||
Check,
|
||||
Flame,
|
||||
X,
|
||||
Tv,
|
||||
Clock,
|
||||
} from 'lucide-react';
|
||||
import { useAppStore } from '../store/appStore';
|
||||
import { computeUptimeSeconds, formatUptimeCompact, useNowTick } from '../lib/time';
|
||||
import type { ChannelCard as ChannelCardType } from '../types';
|
||||
|
||||
function rankBadgeStyle(rank: number): string {
|
||||
if (rank === 1) {
|
||||
return 'bg-gradient-to-r from-amber-400 to-yellow-300 text-[#101318] shadow-[0_0_12px_rgba(251,191,36,0.45)]';
|
||||
}
|
||||
if (rank === 2) {
|
||||
return 'bg-gradient-to-r from-slate-200 to-slate-400 text-[#101318]';
|
||||
}
|
||||
if (rank === 3) {
|
||||
return 'bg-gradient-to-r from-orange-400 to-amber-600 text-[#101318]';
|
||||
}
|
||||
return 'bg-[#101318]/85 text-[#60E0B1] border border-[#247553]/60';
|
||||
}
|
||||
|
||||
export const ChannelList: React.FC = () => {
|
||||
const topTrChannels = useAppStore((s) => s.topTrChannels);
|
||||
const isLoadingTopTr = useAppStore((s) => s.isLoadingTopTr);
|
||||
const loadTopTrChannels = useAppStore((s) => s.loadTopTrChannels);
|
||||
const channels = useAppStore((s) => s.channels);
|
||||
const activeChannel = useAppStore((s) => s.activeChannel);
|
||||
const playChannel = useAppStore((s) => s.playChannel);
|
||||
const followChannel = useAppStore((s) => s.followChannel);
|
||||
const kickProfile = useAppStore((s) => s.kickProfile);
|
||||
|
||||
const [filterQuery, setFilterQuery] = useState('');
|
||||
const nowMs = useNowTick(topTrChannels.some((c) => c.is_live && !!c.started_at), 30000);
|
||||
const [quickSlug, setQuickSlug] = useState('');
|
||||
|
||||
const followedSlugSet = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
channels.forEach((c) => set.add(c.channel_name.toLowerCase()));
|
||||
return set;
|
||||
}, [channels]);
|
||||
|
||||
const filteredTop = useMemo(() => {
|
||||
const q = filterQuery.trim().toLowerCase();
|
||||
if (!q) return topTrChannels;
|
||||
return topTrChannels.filter(
|
||||
(ch) =>
|
||||
ch.channel_name.toLowerCase().includes(q) ||
|
||||
ch.title.toLowerCase().includes(q) ||
|
||||
ch.category.toLowerCase().includes(q)
|
||||
);
|
||||
}, [topTrChannels, filterQuery]);
|
||||
|
||||
const totalTopViewers = useMemo(
|
||||
() => topTrChannels.reduce((acc, ch) => acc + (ch.viewers || 0), 0),
|
||||
[topTrChannels]
|
||||
);
|
||||
|
||||
const handleQuickWatch = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const cleaned = quickSlug
|
||||
.trim()
|
||||
.replace(/^@/, '')
|
||||
.replace(/^https?:\/\/(www\.)?kick\.com\//i, '')
|
||||
.replace(/\/+$/, '')
|
||||
.toLowerCase();
|
||||
if (!cleaned) return;
|
||||
|
||||
const existing =
|
||||
topTrChannels.find((c) => c.channel_name.toLowerCase() === cleaned) ||
|
||||
channels.find((c) => c.channel_name.toLowerCase() === cleaned);
|
||||
|
||||
const target: ChannelCardType = existing || {
|
||||
channel_name: cleaned,
|
||||
is_live: true,
|
||||
title: '',
|
||||
category: '',
|
||||
viewers: 0,
|
||||
verified: false,
|
||||
avatar_url: '',
|
||||
is_playing: false,
|
||||
};
|
||||
|
||||
setQuickSlug('');
|
||||
void playChannel(target);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col h-full overflow-hidden bg-[#101318]">
|
||||
{/* Showcase Header */}
|
||||
<div className="p-4 border-b border-[#2E3542]/50 bg-[#11151D]/95 backdrop-blur-sm z-10 shrink-0 flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-[#247553]/45 to-[#15241F] border border-[#60E0B1]/45 flex items-center justify-center shrink-0 shadow-[0_0_16px_rgba(96,224,177,0.2)]">
|
||||
<Flame className="w-5 h-5 text-[#60E0B1]" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h1 className="text-sm sm:text-base font-extrabold text-slate-100 tracking-wide">
|
||||
Kick Türkiye · Anlık En Çok İzlenen 12 Kanal
|
||||
</h1>
|
||||
{totalTopViewers > 0 && (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-[#1B222D] border border-[#2E3542] text-[11px] font-bold text-[#60E0B1]">
|
||||
<Users className="w-3 h-3" />
|
||||
{totalTopViewers.toLocaleString('tr-TR')} izleyici
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-[11px] text-slate-400">
|
||||
Takip ettiklerin soldaki panelde, Türkiye canlı sıralaması burada. Tek tıkla gecikmesiz izle.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => void loadTopTrChannels()}
|
||||
disabled={isLoadingTopTr}
|
||||
className="h-9 px-3.5 rounded-xl bg-[#151A23] border border-[#2E3542] hover:border-[#60E0B1]/50 text-xs font-semibold text-slate-200 hover:text-[#60E0B1] transition-colors flex items-center gap-2 disabled:opacity-50 shrink-0"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${isLoadingTopTr ? 'animate-spin text-[#60E0B1]' : ''}`} />
|
||||
<span>Sıralamayı Yenile</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filter + Direct Channel Quick-Open Bar */}
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<div className="relative flex-1 min-w-[200px]">
|
||||
<Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
value={filterQuery}
|
||||
onChange={(e) => setFilterQuery(e.target.value)}
|
||||
placeholder="Top 12 içinde yayıncı, kategori veya başlık ara..."
|
||||
className="w-full h-9 pl-9 pr-8 rounded-xl bg-[#151921] border border-[#2E3542] text-xs text-slate-100 placeholder-slate-500 focus:outline-none focus:border-[#60E0B1] transition-all"
|
||||
/>
|
||||
{filterQuery && (
|
||||
<button
|
||||
onClick={() => setFilterQuery('')}
|
||||
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-200"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleQuickWatch} className="flex items-center gap-1.5">
|
||||
<input
|
||||
type="text"
|
||||
value={quickSlug}
|
||||
onChange={(e) => setQuickSlug(e.target.value)}
|
||||
placeholder="Özel kanal aç (örn: elraenn)..."
|
||||
className="w-48 sm:w-56 h-9 px-3 rounded-xl bg-[#151921] border border-[#2E3542] text-xs text-slate-100 placeholder-slate-500 focus:outline-none focus:border-[#60E0B1]"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!quickSlug.trim()}
|
||||
className="h-9 px-3.5 rounded-xl bg-gradient-to-r from-[#247553] to-[#4CE0AC] text-[#101318] text-xs font-extrabold hover:brightness-110 disabled:opacity-45 transition-all flex items-center gap-1.5 shrink-0"
|
||||
>
|
||||
<Play className="w-3.5 h-3.5 fill-current" />
|
||||
<span>İzle</span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Top 12 Showcase Grid */}
|
||||
<div className="flex-1 overflow-y-auto p-4 custom-scrollbar">
|
||||
{isLoadingTopTr && topTrChannels.length === 0 ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
{Array.from({ length: 12 }).map((_, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="rounded-2xl bg-[#151921] border border-[#2E3542]/60 overflow-hidden animate-pulse"
|
||||
>
|
||||
<div className="w-full aspect-video bg-[#1B202A]" />
|
||||
<div className="p-3.5 space-y-2">
|
||||
<div className="h-3.5 w-2/3 bg-[#1B202A] rounded" />
|
||||
<div className="h-3 w-full bg-[#1B202A] rounded" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : filteredTop.length > 0 ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
{filteredTop.map((channel) => {
|
||||
const rank =
|
||||
topTrChannels.findIndex(
|
||||
(c) => c.channel_name.toLowerCase() === channel.channel_name.toLowerCase()
|
||||
) + 1;
|
||||
const isPlayingHere =
|
||||
activeChannel?.channel_name.toLowerCase() === channel.channel_name.toLowerCase();
|
||||
const isInList = followedSlugSet.has(channel.channel_name.toLowerCase());
|
||||
|
||||
return (
|
||||
<div
|
||||
key={channel.channel_name}
|
||||
onClick={() => void playChannel(channel)}
|
||||
className={`group rounded-2xl overflow-hidden border cursor-pointer transition-all duration-200 flex flex-col bg-[#151921] ${
|
||||
isPlayingHere
|
||||
? 'border-[#60E0B1] shadow-[0_0_24px_rgba(96,224,177,0.22)] ring-1 ring-[#60E0B1]/30'
|
||||
: 'border-[#28303E] hover:border-[#60E0B1]/60 hover:-translate-y-0.5 hover:shadow-[0_12px_28px_rgba(0,0,0,0.45)]'
|
||||
}`}
|
||||
>
|
||||
{/* 16:9 Live Preview */}
|
||||
<div className="relative w-full aspect-video bg-[#0B0E14] overflow-hidden">
|
||||
{channel.thumbnail_url ? (
|
||||
<img
|
||||
src={channel.thumbnail_url}
|
||||
alt={channel.channel_name}
|
||||
loading="lazy"
|
||||
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full bg-gradient-to-br from-[#172821] via-[#131822] to-[#0E1117] flex items-center justify-center">
|
||||
<Tv className="w-10 h-10 text-[#60E0B1]/40" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Gradient Scrim */}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-black/45 pointer-events-none" />
|
||||
|
||||
{/* Top-left Rank + CANLI Pill */}
|
||||
<div className="absolute top-2.5 left-2.5 flex items-center gap-1.5">
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-lg text-[11px] font-black tracking-tight ${rankBadgeStyle(
|
||||
rank
|
||||
)}`}
|
||||
>
|
||||
#{rank}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-lg bg-rose-600/90 text-white text-[10px] font-extrabold tracking-wider uppercase shadow-sm">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-white animate-pulse" />
|
||||
CANLI
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Top-right quick actions on hover */}
|
||||
<div
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="absolute top-2.5 right-2.5 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
{!isInList ? (
|
||||
<button
|
||||
onClick={() =>
|
||||
void followChannel(
|
||||
channel.channel_name,
|
||||
true,
|
||||
channel.category || undefined
|
||||
)
|
||||
}
|
||||
title={kickProfile ? 'Kick hesabında takip et' : 'Sol listeye ekle'}
|
||||
className="p-1.5 rounded-lg bg-black/75 text-slate-200 hover:text-[#60E0B1] border border-white/15 transition-colors"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
) : (
|
||||
<span
|
||||
title="Listende kayıtlı"
|
||||
className="p-1.5 rounded-lg bg-[#247553]/85 text-[#60E0B1] border border-[#60E0B1]/40"
|
||||
>
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
onClick={() => void playChannel(channel, true)}
|
||||
title="Harici oynatıcıda aç"
|
||||
className="p-1.5 rounded-lg bg-black/75 text-slate-200 hover:text-[#60E0B1] border border-white/15 transition-colors"
|
||||
>
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Bottom-left Stream Uptime */}
|
||||
{channel.is_live &&
|
||||
computeUptimeSeconds(channel.started_at, undefined, nowMs) > 0 && (
|
||||
<div
|
||||
title="Canlı yayın süresi"
|
||||
className="absolute bottom-2.5 left-2.5 inline-flex items-center gap-1 px-2 py-1 rounded-lg bg-black/75 backdrop-blur-sm border border-white/10 text-[11px] font-semibold text-slate-100"
|
||||
>
|
||||
<Clock className="w-3 h-3 text-[#60E0B1]" />
|
||||
<span>
|
||||
{formatUptimeCompact(
|
||||
computeUptimeSeconds(channel.started_at, undefined, nowMs)
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Bottom-right Viewer Count */}
|
||||
<div className="absolute bottom-2.5 right-2.5 inline-flex items-center gap-1.5 px-2 py-1 rounded-lg bg-black/75 backdrop-blur-sm border border-white/10 text-[11px] font-bold text-slate-100">
|
||||
<Users className="w-3 h-3 text-[#60E0B1]" />
|
||||
<span>{(channel.viewers || 0).toLocaleString('tr-TR')}</span>
|
||||
</div>
|
||||
|
||||
{/* Center Play Overlay on Hover */}
|
||||
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
|
||||
<div className="w-12 h-12 rounded-full bg-[#4CE0AC]/90 text-[#0B0E14] flex items-center justify-center shadow-[0_0_24px_rgba(76,224,172,0.55)]">
|
||||
<Play className="w-5 h-5 fill-current ml-0.5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Card Footer */}
|
||||
<div className="p-3 flex items-start gap-2.5">
|
||||
<div className="w-9 h-9 rounded-xl overflow-hidden bg-[#1B202A] border border-[#2E3542] shrink-0 flex items-center justify-center">
|
||||
{channel.avatar_url ? (
|
||||
<img
|
||||
src={channel.avatar_url}
|
||||
alt={channel.channel_name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-xs font-bold text-slate-300 uppercase">
|
||||
{channel.channel_name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h3 className="text-xs font-extrabold text-slate-100 group-hover:text-[#60E0B1] transition-colors truncate">
|
||||
{channel.channel_name}
|
||||
</h3>
|
||||
{isPlayingHere && (
|
||||
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-[#247553]/40 text-[#60E0B1] border border-[#247553]/60 shrink-0">
|
||||
OYNATILIYOR
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-[11px] text-slate-300 line-clamp-1 mt-0.5">
|
||||
{channel.title || 'Canlı Yayın'}
|
||||
</p>
|
||||
|
||||
{channel.category && (
|
||||
<span className="inline-block mt-1.5 px-2 py-0.5 rounded-md bg-[#1B202A] border border-[#2A313E] text-[10px] font-medium text-[#60E0B1]/90 truncate max-w-full">
|
||||
{channel.category}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-full flex flex-col items-center justify-center text-center p-8">
|
||||
<div className="w-16 h-16 rounded-2xl bg-[#151921] border border-[#2E3542] flex items-center justify-center mb-4">
|
||||
<Tv className="w-8 h-8 text-[#60E0B1]/60" />
|
||||
</div>
|
||||
<h3 className="text-base font-semibold text-slate-200">
|
||||
{filterQuery ? 'Eşleşen Kanal Bulunamadı' : 'Türkiye Canlı Listesi Alınamadı'}
|
||||
</h3>
|
||||
<p className="text-xs text-slate-400 max-w-sm mt-1.5 mb-5">
|
||||
{filterQuery
|
||||
? `"${filterQuery}" aramasıyla eşleşen bir yayın bulunamadı.`
|
||||
: 'Kick Türkiye yayın listesi şu an alınamadı. Yenileyerek tekrar deneyebilirsiniz.'}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => (filterQuery ? setFilterQuery('') : void loadTopTrChannels())}
|
||||
className="px-4 py-2 rounded-xl bg-gradient-to-r from-[#247553] to-[#4CE0AC] text-[#101318] text-xs font-bold hover:brightness-110 transition-all flex items-center gap-2"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
<span>{filterQuery ? 'Filtreyi Temizle' : 'Tekrar Yükle'}</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
138
src/components/ChatBadge.tsx
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import React from 'react';
|
||||
import type { ChatBadge as ChatBadgeType } from '../types';
|
||||
|
||||
interface ChatBadgeProps {
|
||||
badge: ChatBadgeType;
|
||||
}
|
||||
|
||||
const BASE =
|
||||
'inline-flex items-center justify-center h-4 min-w-4 px-0.5 rounded-[3px] text-[9px] font-black leading-none select-none shrink-0';
|
||||
|
||||
/** Kick-style SVG badges: colours mirror the original chat badge palette. */
|
||||
export const ChatBadge: React.FC<ChatBadgeProps> = ({ badge }) => {
|
||||
const type = (badge.type || '').toLowerCase();
|
||||
const title = badge.text || type;
|
||||
const count = badge.count ?? null;
|
||||
|
||||
if (type === 'subscriber') {
|
||||
return (
|
||||
<span
|
||||
title={count ? `Abone · ${count} ay` : 'Abone'}
|
||||
className={`${BASE} bg-[#1f6f4a] text-[#b8ffd9] border border-[#60E0B1]/50`}
|
||||
>
|
||||
{count && count > 0 ? `${count}M` : 'SUB'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === 'sub_gifter') {
|
||||
return (
|
||||
<span
|
||||
title={count ? `Hediye abone · ${count}` : 'Hediye abone'}
|
||||
className={`${BASE} bg-[#6b3fa0] text-white border border-[#b98cff]/50`}
|
||||
>
|
||||
<svg viewBox="0 0 16 16" className="w-3 h-3" fill="currentColor" aria-hidden>
|
||||
<path d="M2 6h12v2H2zM3 9h10v5H3zM7 6h2v8H7z" />
|
||||
<path d="M8 6S6.5 2 4.8 2.6C3.4 3.1 4 6 8 6zm0 0s1.5-4 3.2-3.4C12.6 3.1 12 6 8 6z" />
|
||||
</svg>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const palette: Record<string, { bg: string; fg: string; icon: React.ReactNode; label: string }> = {
|
||||
broadcaster: {
|
||||
bg: '#b91c1c',
|
||||
fg: '#fff',
|
||||
label: 'Yayıncı',
|
||||
icon: (
|
||||
<svg viewBox="0 0 16 16" className="w-3 h-3" fill="currentColor" aria-hidden>
|
||||
<path d="M2 4h12v8H2z" opacity=".25" />
|
||||
<path d="M8 3l1.6 3.3 3.6.5-2.6 2.5.6 3.6L8 11.2 4.8 12.9l.6-3.6L2.8 6.8l3.6-.5z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
moderator: {
|
||||
bg: '#1d4ed8',
|
||||
fg: '#fff',
|
||||
label: 'Moderatör',
|
||||
icon: (
|
||||
<svg viewBox="0 0 16 16" className="w-3 h-3" fill="currentColor" aria-hidden>
|
||||
<path d="M11.6 2.2l2.2 2.2-7 7-2.9.7.7-2.9zM2 13h12v1.4H2z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
vip: {
|
||||
bg: '#7c3aed',
|
||||
fg: '#fff',
|
||||
label: 'VIP',
|
||||
icon: (
|
||||
<svg viewBox="0 0 16 16" className="w-3 h-3" fill="currentColor" aria-hidden>
|
||||
<path d="M8 2l2.2 3.9L14.5 7 8 14 1.5 7l4.3-1.1z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
founder: {
|
||||
bg: '#a16207',
|
||||
fg: '#fff',
|
||||
label: 'Kurucu',
|
||||
icon: (
|
||||
<svg viewBox="0 0 16 16" className="w-3 h-3" fill="currentColor" aria-hidden>
|
||||
<path d="M3 3l3 3 2-3 2 3 3-3v8H3z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
og: {
|
||||
bg: '#0f766e',
|
||||
fg: '#fff',
|
||||
label: 'OG',
|
||||
icon: (
|
||||
<svg viewBox="0 0 16 16" className="w-3 h-3" fill="currentColor" aria-hidden>
|
||||
<path d="M8 2l5 2v4c0 3-2.2 5-5 6-2.8-1-5-3-5-6V4z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
verified: {
|
||||
bg: '#1d9bf0',
|
||||
fg: '#fff',
|
||||
label: 'Onaylı',
|
||||
icon: (
|
||||
<svg viewBox="0 0 16 16" className="w-3 h-3" fill="currentColor" aria-hidden>
|
||||
<path d="M8 1l2 1.6 2.5-.2.6 2.4 2 1.5-1 2.3 1 2.3-2 1.5-.6 2.4-2.5-.2L8 15l-2-1.6-2.5.2-.6-2.4-2-1.5 1-2.3-1-2.3 2-1.5.6-2.4L6.5 2z" />
|
||||
<path d="M4.8 8.2l1.8 1.8 3.8-3.8" stroke="#1d9bf0" strokeWidth="1.4" fill="none" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
staff: {
|
||||
bg: '#374151',
|
||||
fg: '#fff',
|
||||
label: 'Staff',
|
||||
icon: (
|
||||
<svg viewBox="0 0 16 16" className="w-3 h-3" fill="currentColor" aria-hidden>
|
||||
<path d="M8 2l5 2v5c0 2.5-2 4-5 5-3-1-5-2.5-5-5V4z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
bot: {
|
||||
bg: '#4b5563',
|
||||
fg: '#fff',
|
||||
label: 'Bot',
|
||||
icon: (
|
||||
<svg viewBox="0 0 16 16" className="w-3 h-3" fill="currentColor" aria-hidden>
|
||||
<path d="M4 6h8v6H4zM7 3h2v3H7zM2 8h2v2H2zm10 0h2v2h-2z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
const style = palette[type] ?? { bg: '#374151', fg: '#e5e7eb', label: title, icon: null };
|
||||
|
||||
return (
|
||||
<span
|
||||
title={title || style.label}
|
||||
className={BASE}
|
||||
style={{ backgroundColor: style.bg, color: style.fg, border: '1px solid rgba(255,255,255,0.18)' }}
|
||||
>
|
||||
{style.icon}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
1075
src/components/ChatDrawer.tsx
Normal file
535
src/components/LiveChannelsDrawer.tsx
Normal file
|
|
@ -0,0 +1,535 @@
|
|||
import React, { useMemo, useState } from 'react';
|
||||
import {
|
||||
Radio,
|
||||
Users,
|
||||
X,
|
||||
Play,
|
||||
Search,
|
||||
RefreshCw,
|
||||
Plus,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ArrowDownToLine,
|
||||
Sprout,
|
||||
Heart,
|
||||
Clock,
|
||||
} from 'lucide-react';
|
||||
import { useAppStore } from '../store/appStore';
|
||||
import { computeUptimeSeconds, formatUptimeCompact, useNowTick } from '../lib/time';
|
||||
|
||||
function formatViewerCompact(count: number): string {
|
||||
if (count >= 1000) {
|
||||
return `${(count / 1000).toFixed(count >= 10000 ? 0 : 1)}B`;
|
||||
}
|
||||
return count.toLocaleString('tr-TR');
|
||||
}
|
||||
|
||||
export const LiveChannelsDrawer: React.FC = () => {
|
||||
const isLiveDrawerOpen = useAppStore((s) => s.isLiveDrawerOpen);
|
||||
const toggleLiveDrawer = useAppStore((s) => s.toggleLiveDrawer);
|
||||
const channels = useAppStore((s) => s.channels);
|
||||
const activeChannel = useAppStore((s) => s.activeChannel);
|
||||
const playChannel = useAppStore((s) => s.playChannel);
|
||||
const refreshChannels = useAppStore((s) => s.refreshChannels);
|
||||
const isLoadingChannels = useAppStore((s) => s.isLoadingChannels);
|
||||
const kickProfile = useAppStore((s) => s.kickProfile);
|
||||
const syncKickFollows = useAppStore((s) => s.syncKickFollows);
|
||||
const kickBusy = useAppStore((s) => s.kickBusy);
|
||||
const addChannel = useAppStore((s) => s.addChannel);
|
||||
const followChannel = useAppStore((s) => s.followChannel);
|
||||
const smallTrChannels = useAppStore((s) => s.smallTrChannels);
|
||||
const isLoadingSmallTr = useAppStore((s) => s.isLoadingSmallTr);
|
||||
const loadSmallTrChannels = useAppStore((s) => s.loadSmallTrChannels);
|
||||
|
||||
const [filterText, setFilterText] = useState('');
|
||||
const [showAddInput, setShowAddInput] = useState(false);
|
||||
const [newSlug, setNewSlug] = useState('');
|
||||
const [addingBusy, setAddingBusy] = useState(false);
|
||||
const [showOffline, setShowOffline] = useState(false);
|
||||
const [showSmallSupport, setShowSmallSupport] = useState(true);
|
||||
const nowMs = useNowTick(isLiveDrawerOpen, 30000);
|
||||
|
||||
const query = filterText.trim().toLowerCase();
|
||||
|
||||
const liveChannels = useMemo(
|
||||
() =>
|
||||
channels
|
||||
.filter((c) => {
|
||||
if (!c.is_live) return false;
|
||||
if (!query) return true;
|
||||
return (
|
||||
c.channel_name.toLowerCase().includes(query) ||
|
||||
c.title.toLowerCase().includes(query) ||
|
||||
c.category.toLowerCase().includes(query)
|
||||
);
|
||||
})
|
||||
.sort((a, b) => (b.viewers || 0) - (a.viewers || 0)),
|
||||
[channels, query]
|
||||
);
|
||||
|
||||
const offlineChannels = useMemo(
|
||||
() =>
|
||||
channels
|
||||
.filter((c) => {
|
||||
if (c.is_live) return false;
|
||||
if (!query) return true;
|
||||
return c.channel_name.toLowerCase().includes(query);
|
||||
})
|
||||
.sort((a, b) => a.channel_name.localeCompare(b.channel_name)),
|
||||
[channels, query]
|
||||
);
|
||||
|
||||
const totalLiveCount = useMemo(
|
||||
() => channels.filter((c) => c.is_live).length,
|
||||
[channels]
|
||||
);
|
||||
|
||||
const supportChannels = useMemo(() => {
|
||||
const followedSet = new Set(channels.map((c) => c.channel_name.toLowerCase()));
|
||||
return smallTrChannels.filter((c) => {
|
||||
if (followedSet.has(c.channel_name.toLowerCase())) return false;
|
||||
if (!query) return true;
|
||||
return (
|
||||
c.channel_name.toLowerCase().includes(query) ||
|
||||
c.title.toLowerCase().includes(query) ||
|
||||
c.category.toLowerCase().includes(query)
|
||||
);
|
||||
});
|
||||
}, [smallTrChannels, channels, query]);
|
||||
|
||||
if (!isLiveDrawerOpen) return null;
|
||||
|
||||
const handleQuickAdd = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const clean = newSlug.trim();
|
||||
if (!clean || addingBusy) return;
|
||||
setAddingBusy(true);
|
||||
const ok = await addChannel(clean);
|
||||
setAddingBusy(false);
|
||||
if (ok) {
|
||||
setNewSlug('');
|
||||
setShowAddInput(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className="w-72 bg-gradient-to-b from-[#141922] via-[#11151D] to-[#0E1117] border-r border-[#247553]/35 flex flex-col h-full z-30 shrink-0 select-none shadow-[6px_0_24px_rgba(0,0,0,0.45)]">
|
||||
{/* Studio Header with Subtle Emerald Glow */}
|
||||
<div className="relative px-3.5 py-3 bg-gradient-to-br from-[#172320] via-[#151A22] to-[#12161E] border-b border-[#247553]/40 shrink-0 overflow-hidden">
|
||||
<div className="absolute -top-10 -left-8 w-28 h-28 bg-[#60E0B1]/12 rounded-full blur-2xl pointer-events-none" />
|
||||
|
||||
<div className="relative flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<div className="w-8 h-8 rounded-xl bg-gradient-to-br from-[#247553]/50 to-[#152921] border border-[#60E0B1]/45 flex items-center justify-center shrink-0 shadow-[0_0_12px_rgba(96,224,177,0.2)]">
|
||||
<Radio className="w-4 h-4 text-[#60E0B1] animate-pulse" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<h3 className="text-xs font-extrabold tracking-wide text-slate-100 truncate">
|
||||
Aktif Takip Edilenler
|
||||
</h3>
|
||||
<span className="px-1.5 py-0.5 rounded-full text-[10px] font-extrabold bg-[#247553]/55 text-[#60E0B1] border border-[#60E0B1]/35 leading-none">
|
||||
{totalLiveCount}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[10px] text-slate-400 truncate mt-0.5">
|
||||
{kickProfile ? `@${kickProfile.username} takip listesi` : 'Takip listen · canlı akış'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-0.5 shrink-0">
|
||||
{kickProfile ? (
|
||||
<button
|
||||
onClick={() => void syncKickFollows()}
|
||||
disabled={kickBusy}
|
||||
title="Kick takip listesini senkronize et"
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-[#60E0B1] hover:bg-[#1B222C] transition-colors disabled:opacity-40"
|
||||
>
|
||||
<ArrowDownToLine className={`w-3.5 h-3.5 ${kickBusy ? 'animate-pulse text-[#60E0B1]' : ''}`} />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setShowAddInput((v) => !v)}
|
||||
title="Kanal ekle"
|
||||
className={`p-1.5 rounded-lg transition-colors ${
|
||||
showAddInput
|
||||
? 'bg-[#247553]/40 text-[#60E0B1]'
|
||||
: 'text-slate-400 hover:text-[#60E0B1] hover:bg-[#1B222C]'
|
||||
}`}
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => void refreshChannels()}
|
||||
disabled={isLoadingChannels}
|
||||
title="Canlı durumları yenile"
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-[#60E0B1] hover:bg-[#1B222C] transition-colors disabled:opacity-40"
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-3.5 h-3.5 ${isLoadingChannels ? 'animate-spin text-[#60E0B1]' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => toggleLiveDrawer(false)}
|
||||
title="Paneli Gizle"
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-[#1B222C] transition-colors"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Inline Quick-Add Input (for guest / manual additions) */}
|
||||
{showAddInput && (
|
||||
<form onSubmit={handleQuickAdd} className="mt-2.5 flex items-center gap-1.5">
|
||||
<input
|
||||
type="text"
|
||||
value={newSlug}
|
||||
onChange={(e) => setNewSlug(e.target.value)}
|
||||
placeholder="Kanal adı ekle (örn: hype)..."
|
||||
autoFocus
|
||||
className="flex-1 h-7 px-2.5 rounded-lg bg-[#0F1319] border border-[#2E3542] text-[11px] text-slate-100 placeholder-slate-500 focus:outline-none focus:border-[#60E0B1]"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={addingBusy || !newSlug.trim()}
|
||||
className="h-7 px-2.5 rounded-lg bg-[#247553] text-[#60E0B1] text-[11px] font-bold hover:bg-[#2E9167] hover:text-white disabled:opacity-50 transition-colors"
|
||||
>
|
||||
Ekle
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{/* Instant Filter Input */}
|
||||
<div className="relative mt-2.5">
|
||||
<Search className="w-3.5 h-3.5 text-slate-500 absolute left-2.5 top-1/2 -translate-y-1/2 pointer-events-none" />
|
||||
<input
|
||||
type="text"
|
||||
value={filterText}
|
||||
onChange={(e) => setFilterText(e.target.value)}
|
||||
placeholder="Takip edilenlerde ara..."
|
||||
className="w-full h-7 pl-8 pr-7 rounded-lg bg-[#0E1218]/90 border border-[#28303D] text-[11px] text-slate-200 placeholder-slate-500 focus:outline-none focus:border-[#60E0B1]/70 transition-colors"
|
||||
/>
|
||||
{filterText && (
|
||||
<button
|
||||
onClick={() => setFilterText('')}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-200"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Scrollable Live & Offline Channels List */}
|
||||
<div className="flex-1 overflow-y-auto p-2 space-y-1.5 custom-scrollbar">
|
||||
{liveChannels.length === 0 ? (
|
||||
<div className="py-10 px-4 flex flex-col items-center justify-center text-center">
|
||||
<div className="w-11 h-11 rounded-2xl bg-[#161B24] border border-[#2E3542]/70 flex items-center justify-center mb-2.5">
|
||||
<Radio className="w-5 h-5 text-slate-500" />
|
||||
</div>
|
||||
<p className="text-xs font-semibold text-slate-300">
|
||||
{query ? 'Eşleşen canlı kanal yok' : 'Şu anda canlı yayın yok'}
|
||||
</p>
|
||||
<p className="text-[11px] text-slate-500 mt-1">
|
||||
{query
|
||||
? 'Arama terimini temizleyip tekrar deneyin.'
|
||||
: 'Sağ taraftaki TR Top 12 vitrininden anlık popüler yayınları izleyebilirsiniz.'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
liveChannels.map((ch) => {
|
||||
const isCurrent =
|
||||
activeChannel?.channel_name.toLowerCase() === ch.channel_name.toLowerCase();
|
||||
return (
|
||||
<button
|
||||
key={ch.channel_name}
|
||||
onClick={() => {
|
||||
void playChannel(ch);
|
||||
}}
|
||||
className={`group relative w-full flex items-center gap-2.5 p-2 rounded-xl border text-left transition-all duration-150 ${
|
||||
isCurrent
|
||||
? 'bg-gradient-to-r from-[#172B24] via-[#15221E] to-[#141A22] border-[#60E0B1]/75 shadow-[0_0_18px_rgba(96,224,177,0.18)]'
|
||||
: 'bg-[#151A23]/85 hover:bg-[#1B222E] border-[#262E3B] hover:border-[#60E0B1]/45'
|
||||
}`}
|
||||
>
|
||||
{isCurrent && (
|
||||
<span className="absolute left-0 top-2 bottom-2 w-1 rounded-r-full bg-[#4CE0AC]" />
|
||||
)}
|
||||
|
||||
{/* Avatar with emerald live ring */}
|
||||
<div className="relative shrink-0">
|
||||
<div
|
||||
className={`w-10 h-10 rounded-xl overflow-hidden bg-[#1B202A] flex items-center justify-center border-2 transition-colors ${
|
||||
isCurrent
|
||||
? 'border-[#4CE0AC] shadow-[0_0_10px_rgba(76,224,172,0.35)]'
|
||||
: 'border-[#247553]/70 group-hover:border-[#60E0B1]'
|
||||
}`}
|
||||
>
|
||||
{ch.avatar_url ? (
|
||||
<img
|
||||
src={ch.avatar_url}
|
||||
alt={ch.channel_name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-xs font-bold text-slate-300 uppercase">
|
||||
{ch.channel_name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full bg-[#4CE0AC] border-2 border-[#12161E]" />
|
||||
</div>
|
||||
|
||||
{/* Channel Details */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-1.5">
|
||||
<span
|
||||
className={`text-xs font-bold truncate transition-colors ${
|
||||
isCurrent
|
||||
? 'text-[#60E0B1]'
|
||||
: 'text-slate-100 group-hover:text-[#60E0B1]'
|
||||
}`}
|
||||
>
|
||||
{ch.channel_name}
|
||||
</span>
|
||||
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{isCurrent && (
|
||||
<Play className="w-3 h-3 text-[#60E0B1] fill-current" />
|
||||
)}
|
||||
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-[#0E1218]/90 border border-[#28303D] text-[10px] font-bold text-slate-200">
|
||||
<Users className="w-2.5 h-2.5 text-[#60E0B1]" />
|
||||
{formatViewerCompact(ch.viewers || 0)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-2 mt-0.5">
|
||||
<p className="text-[10px] font-medium text-[#60E0B1]/85 truncate">
|
||||
{ch.category || 'Canlı Yayın'}
|
||||
</p>
|
||||
{computeUptimeSeconds(ch.started_at, undefined, nowMs) > 0 && (
|
||||
<span
|
||||
title="Canlı yayın süresi"
|
||||
className="inline-flex items-center gap-0.5 text-[10px] font-mono text-slate-400 shrink-0"
|
||||
>
|
||||
<Clock className="w-2.5 h-2.5 text-[#60E0B1]/80" />
|
||||
{formatUptimeCompact(computeUptimeSeconds(ch.started_at, undefined, nowMs))}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{ch.title && (
|
||||
<p className="text-[10px] text-slate-400 truncate mt-0.5">
|
||||
{ch.title}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
||||
{/* Collapsible Offline Followed Section */}
|
||||
{offlineChannels.length > 0 && (
|
||||
<div className="pt-2 mt-2 border-t border-[#262E3B]/70">
|
||||
<button
|
||||
onClick={() => setShowOffline((v) => !v)}
|
||||
className="w-full flex items-center justify-between px-2 py-1.5 rounded-lg text-[11px] font-semibold text-slate-400 hover:text-slate-200 hover:bg-[#171C26] transition-colors"
|
||||
>
|
||||
<span className="flex items-center gap-1.5">
|
||||
{showOffline ? (
|
||||
<ChevronDown className="w-3.5 h-3.5 text-slate-500" />
|
||||
) : (
|
||||
<ChevronRight className="w-3.5 h-3.5 text-slate-500" />
|
||||
)}
|
||||
Çevrimdışı Kanallar
|
||||
</span>
|
||||
<span className="px-1.5 py-0.5 rounded bg-[#1B202A] text-[10px] text-slate-400">
|
||||
{offlineChannels.length}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{showOffline && (
|
||||
<div className="mt-1 space-y-1">
|
||||
{offlineChannels.map((ch) => (
|
||||
<button
|
||||
key={ch.channel_name}
|
||||
onClick={() => void playChannel(ch)}
|
||||
title={`${ch.channel_name} (Çevrimdışı)`}
|
||||
className="w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg hover:bg-[#181D26] text-left transition-colors opacity-70 hover:opacity-100"
|
||||
>
|
||||
<div className="w-7 h-7 rounded-lg overflow-hidden bg-[#1B202A] border border-[#2A313E] shrink-0 flex items-center justify-center grayscale">
|
||||
{ch.avatar_url ? (
|
||||
<img
|
||||
src={ch.avatar_url}
|
||||
alt={ch.channel_name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-[10px] font-bold text-slate-400 uppercase">
|
||||
{ch.channel_name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs font-medium text-slate-400 truncate flex-1">
|
||||
{ch.channel_name}
|
||||
</span>
|
||||
<span className="text-[9px] uppercase tracking-wide text-slate-500 font-semibold">
|
||||
Kapalı
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Small Turkish Streamer Support Section (5-30 viewers, visible ONLY when drawer is open) */}
|
||||
<div className="pt-2 mt-2 border-t border-[#247553]/35">
|
||||
<div className="flex items-center justify-between gap-1 px-1">
|
||||
<button
|
||||
onClick={() => setShowSmallSupport((v) => !v)}
|
||||
className="flex-1 flex items-center justify-between px-1.5 py-1.5 rounded-lg text-[11px] font-bold text-[#60E0B1]/90 hover:text-[#60E0B1] hover:bg-[#17211F] transition-colors min-w-0"
|
||||
>
|
||||
<span className="flex items-center gap-1.5 truncate">
|
||||
{showSmallSupport ? (
|
||||
<ChevronDown className="w-3.5 h-3.5 text-[#60E0B1]/80 shrink-0" />
|
||||
) : (
|
||||
<ChevronRight className="w-3.5 h-3.5 text-[#60E0B1]/80 shrink-0" />
|
||||
)}
|
||||
<Sprout className="w-3.5 h-3.5 text-[#60E0B1] shrink-0" />
|
||||
<span className="truncate">Ufak Yayıncılar</span>
|
||||
</span>
|
||||
<span className="px-1.5 py-0.5 rounded bg-[#182923] border border-[#247553]/50 text-[10px] text-[#60E0B1] shrink-0 ml-1">
|
||||
{supportChannels.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => void loadSmallTrChannels()}
|
||||
disabled={isLoadingSmallTr}
|
||||
title="Ufak yayıncıları yenile (rastgele 15)"
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-[#60E0B1] hover:bg-[#1B222C] transition-colors disabled:opacity-40 shrink-0"
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-3 h-3 ${isLoadingSmallTr ? 'animate-spin text-[#60E0B1]' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showSmallSupport && (
|
||||
<div className="mt-1.5 space-y-1.5">
|
||||
{supportChannels.length === 0 ? (
|
||||
<p className="px-2 py-2 text-[11px] text-slate-500 text-center">
|
||||
{isLoadingSmallTr
|
||||
? 'Ufak yayıncılar taranıyor…'
|
||||
: 'Şu an ufak yayıncı bulunamadı'}
|
||||
</p>
|
||||
) : (
|
||||
supportChannels.map((ch) => {
|
||||
const isCurrent =
|
||||
activeChannel?.channel_name.toLowerCase() === ch.channel_name.toLowerCase();
|
||||
return (
|
||||
<div
|
||||
key={`support-${ch.channel_name}`}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => void playChannel(ch)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
void playChannel(ch);
|
||||
}
|
||||
}}
|
||||
className={`group relative w-full flex items-center gap-2.5 p-2 rounded-xl border text-left cursor-pointer transition-all duration-150 ${
|
||||
isCurrent
|
||||
? 'bg-gradient-to-r from-[#172B24] via-[#15221E] to-[#141A22] border-[#60E0B1]/75 shadow-[0_0_16px_rgba(96,224,177,0.16)]'
|
||||
: 'bg-[#141922]/85 hover:bg-[#1A212C] border-[#252D3A] hover:border-[#60E0B1]/45'
|
||||
}`}
|
||||
>
|
||||
<div className="relative shrink-0">
|
||||
<div className="w-8 h-8 rounded-lg overflow-hidden bg-[#1B202A] border border-[#247553]/70 flex items-center justify-center">
|
||||
{ch.avatar_url ? (
|
||||
<img
|
||||
src={ch.avatar_url}
|
||||
alt={ch.channel_name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-[10px] font-bold text-slate-300 uppercase">
|
||||
{ch.channel_name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-[#4CE0AC] border-2 border-[#12161E]" />
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-1">
|
||||
<span
|
||||
className={`text-xs font-bold truncate transition-colors ${
|
||||
isCurrent
|
||||
? 'text-[#60E0B1]'
|
||||
: 'text-slate-100 group-hover:text-[#60E0B1]'
|
||||
}`}
|
||||
>
|
||||
{ch.channel_name}
|
||||
</span>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void followChannel(ch.channel_name, true, ch.category || undefined);
|
||||
}}
|
||||
title={kickProfile ? 'Kick hesabında takip et' : 'Takip listesine ekle'}
|
||||
className="opacity-0 group-hover:opacity-100 p-1 rounded-md bg-[#0E1218]/90 border border-[#28303D] text-slate-400 hover:text-rose-400 hover:border-rose-500/40 transition-all"
|
||||
>
|
||||
<Heart className="w-2.5 h-2.5" />
|
||||
</button>
|
||||
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-[#0E1218]/90 border border-[#247553]/50 text-[10px] font-bold text-[#60E0B1]">
|
||||
<Users className="w-2.5 h-2.5" />
|
||||
{ch.viewers}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-2 mt-0.5">
|
||||
<p className="text-[10px] font-medium text-slate-400 truncate">
|
||||
{ch.category || 'Türkçe Yayın'}
|
||||
</p>
|
||||
{computeUptimeSeconds(ch.started_at, undefined, nowMs) > 0 && (
|
||||
<span
|
||||
title="Canlı yayın süresi"
|
||||
className="inline-flex items-center gap-0.5 text-[10px] font-mono text-slate-400 shrink-0"
|
||||
>
|
||||
<Clock className="w-2.5 h-2.5 text-[#60E0B1]/80" />
|
||||
{formatUptimeCompact(
|
||||
computeUptimeSeconds(ch.started_at, undefined, nowMs)
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{ch.title && (
|
||||
<p className="text-[10px] text-slate-500 truncate mt-0.5">
|
||||
{ch.title}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
282
src/components/MpvViewport.tsx
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { tauriApi } from '../lib/tauri';
|
||||
|
||||
interface MpvViewportProps {
|
||||
slotId?: string;
|
||||
visible: boolean;
|
||||
aboveParent?: boolean;
|
||||
className?: string;
|
||||
onClick?: () => void;
|
||||
onDoubleClick?: () => void;
|
||||
onMouseMove?: () => void;
|
||||
onMouseLeave?: () => void;
|
||||
onWheel?: (event: React.WheelEvent<HTMLDivElement>) => void;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
let transparentHolders = 0;
|
||||
|
||||
function acquireTransparentBackdrop(): void {
|
||||
transparentHolders += 1;
|
||||
document.documentElement.classList.add('mpv-transparent');
|
||||
}
|
||||
|
||||
function releaseTransparentBackdrop(): void {
|
||||
transparentHolders = Math.max(0, transparentHolders - 1);
|
||||
if (transparentHolders === 0) {
|
||||
document.documentElement.classList.remove('mpv-transparent');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transparent DOM hole over the Win32 native `libmpv` child HWND.
|
||||
* Tracks container coordinates with `ResizeObserver` + DPI scale factor and forwards
|
||||
* physical pixel geometry to Rust's `SetWindowPos` without flooding IPC.
|
||||
*/
|
||||
export const MpvViewport: React.FC<MpvViewportProps> = ({
|
||||
slotId = 'main',
|
||||
visible,
|
||||
aboveParent = false,
|
||||
className = '',
|
||||
onClick,
|
||||
onDoubleClick,
|
||||
onMouseMove,
|
||||
onMouseLeave,
|
||||
onWheel,
|
||||
children,
|
||||
}) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const lastSentRef = useRef<{
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
scale: number;
|
||||
aboveParent: boolean;
|
||||
} | null>(null);
|
||||
const [surfaceReady, setSurfaceReady] = useState(false);
|
||||
const visibleRef = useRef(visible);
|
||||
visibleRef.current = visible;
|
||||
const aboveParentRef = useRef(aboveParent);
|
||||
aboveParentRef.current = aboveParent;
|
||||
const surfaceReadyRef = useRef(surfaceReady);
|
||||
surfaceReadyRef.current = surfaceReady;
|
||||
const revealSeqRef = useRef(0);
|
||||
const revealInFlightRef = useRef(false);
|
||||
|
||||
const punchThrough = visible && !aboveParent && surfaceReady;
|
||||
|
||||
// Enable WebView2 background transparency ONLY AFTER native behind-parent HWND is positioned & shown
|
||||
useLayoutEffect(() => {
|
||||
if (!punchThrough) return;
|
||||
acquireTransparentBackdrop();
|
||||
return () => {
|
||||
releaseTransparentBackdrop();
|
||||
};
|
||||
}, [punchThrough]);
|
||||
|
||||
// Strictly order bounds -> show -> punch-through transparency on visibility or mode changes
|
||||
useLayoutEffect(() => {
|
||||
let cancelled = false;
|
||||
const seq = ++revealSeqRef.current;
|
||||
revealInFlightRef.current = false;
|
||||
setSurfaceReady(false);
|
||||
|
||||
if (!visible) {
|
||||
void tauriApi.mpvSetVisible(false, slotId, false).catch(() => {});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
|
||||
const el = containerRef.current;
|
||||
if (!el) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
|
||||
const rect = el.getBoundingClientRect();
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const x = Math.round(rect.left * 100) / 100;
|
||||
const y = Math.round(rect.top * 100) / 100;
|
||||
const w = Math.max(0, Math.round(rect.width * 100) / 100);
|
||||
const h = Math.max(0, Math.round(rect.height * 100) / 100);
|
||||
const targetAbove = Boolean(aboveParent);
|
||||
|
||||
if (w <= 0 || h <= 0) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
|
||||
lastSentRef.current = { x, y, w, h, scale: dpr, aboveParent: targetAbove };
|
||||
revealInFlightRef.current = true;
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
await tauriApi.mpvSetBounds(x, y, w, h, dpr, slotId, targetAbove);
|
||||
if (cancelled || seq !== revealSeqRef.current) return;
|
||||
await tauriApi.mpvSetVisible(true, slotId, targetAbove);
|
||||
if (!cancelled && seq === revealSeqRef.current && !targetAbove) {
|
||||
setSurfaceReady(true);
|
||||
}
|
||||
} catch {
|
||||
/* keep opaque fallback if native host placement fails */
|
||||
} finally {
|
||||
if (seq === revealSeqRef.current) {
|
||||
revealInFlightRef.current = false;
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [visible, slotId, aboveParent]);
|
||||
|
||||
// Synchronize bounding rect -> Win32 SetWindowPos with rAF throttling
|
||||
useEffect(() => {
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
|
||||
let rafId: number | null = null;
|
||||
let unmounted = false;
|
||||
|
||||
const pushBounds = () => {
|
||||
rafId = null;
|
||||
if (unmounted || !containerRef.current) return;
|
||||
|
||||
const rect = containerRef.current.getBoundingClientRect();
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const x = Math.round(rect.left * 100) / 100;
|
||||
const y = Math.round(rect.top * 100) / 100;
|
||||
const w = Math.max(0, Math.round(rect.width * 100) / 100);
|
||||
const h = Math.max(0, Math.round(rect.height * 100) / 100);
|
||||
const targetAbove = Boolean(aboveParentRef.current);
|
||||
const isVisible = Boolean(visibleRef.current);
|
||||
|
||||
const prev = lastSentRef.current;
|
||||
const boundsMatch =
|
||||
prev &&
|
||||
prev.x === x &&
|
||||
prev.y === y &&
|
||||
prev.w === w &&
|
||||
prev.h === h &&
|
||||
prev.scale === dpr &&
|
||||
prev.aboveParent === targetAbove;
|
||||
|
||||
if (w <= 0 || h <= 0) {
|
||||
if (surfaceReadyRef.current) {
|
||||
setSurfaceReady(false);
|
||||
}
|
||||
if (boundsMatch) return;
|
||||
lastSentRef.current = { x, y, w, h, scale: dpr, aboveParent: targetAbove };
|
||||
void tauriApi.mpvSetBounds(x, y, w, h, dpr, slotId, targetAbove).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
const needsReadyReveal = isVisible && !targetAbove && !surfaceReadyRef.current;
|
||||
|
||||
if (boundsMatch && (!needsReadyReveal || revealInFlightRef.current)) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastSentRef.current = { x, y, w, h, scale: dpr, aboveParent: targetAbove };
|
||||
|
||||
if (needsReadyReveal) {
|
||||
const seq = ++revealSeqRef.current;
|
||||
revealInFlightRef.current = true;
|
||||
void (async () => {
|
||||
try {
|
||||
await tauriApi.mpvSetBounds(x, y, w, h, dpr, slotId, false);
|
||||
if (
|
||||
unmounted ||
|
||||
seq !== revealSeqRef.current ||
|
||||
!visibleRef.current ||
|
||||
aboveParentRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await tauriApi.mpvSetVisible(true, slotId, false);
|
||||
if (
|
||||
!unmounted &&
|
||||
seq === revealSeqRef.current &&
|
||||
visibleRef.current &&
|
||||
!aboveParentRef.current
|
||||
) {
|
||||
setSurfaceReady(true);
|
||||
}
|
||||
} catch {
|
||||
/* keep opaque backdrop on IPC failure */
|
||||
} finally {
|
||||
if (seq === revealSeqRef.current) {
|
||||
revealInFlightRef.current = false;
|
||||
}
|
||||
}
|
||||
})();
|
||||
return;
|
||||
}
|
||||
|
||||
void tauriApi.mpvSetBounds(x, y, w, h, dpr, slotId, targetAbove).catch(() => {});
|
||||
};
|
||||
|
||||
const scheduleSync = () => {
|
||||
if (unmounted || rafId !== null) return;
|
||||
rafId = window.requestAnimationFrame(pushBounds);
|
||||
};
|
||||
|
||||
// Force immediate first measurement + follow layout transitions
|
||||
scheduleSync();
|
||||
|
||||
const resizeObserver = new ResizeObserver(scheduleSync);
|
||||
resizeObserver.observe(el);
|
||||
if (el.parentElement) resizeObserver.observe(el.parentElement);
|
||||
const mainEl = el.closest('main');
|
||||
if (mainEl) resizeObserver.observe(mainEl);
|
||||
resizeObserver.observe(document.documentElement);
|
||||
|
||||
window.addEventListener('resize', scheduleSync);
|
||||
window.addEventListener('scroll', scheduleSync, true);
|
||||
|
||||
let unlistenDpi: (() => void) | undefined;
|
||||
void tauriApi
|
||||
.onWindowDpiChanged(() => {
|
||||
lastSentRef.current = null;
|
||||
scheduleSync();
|
||||
})
|
||||
.then((fn) => {
|
||||
if (unmounted) fn();
|
||||
else unlistenDpi = fn;
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
return () => {
|
||||
unmounted = true;
|
||||
if (rafId !== null) window.cancelAnimationFrame(rafId);
|
||||
resizeObserver.disconnect();
|
||||
window.removeEventListener('resize', scheduleSync);
|
||||
window.removeEventListener('scroll', scheduleSync, true);
|
||||
unlistenDpi?.();
|
||||
lastSentRef.current = null;
|
||||
revealInFlightRef.current = false;
|
||||
void tauriApi.mpvSetVisible(false, slotId, false).catch(() => {});
|
||||
};
|
||||
}, [slotId]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
onClick={onClick}
|
||||
onDoubleClick={onDoubleClick}
|
||||
onMouseMove={onMouseMove}
|
||||
onMouseLeave={onMouseLeave}
|
||||
onWheel={onWheel}
|
||||
className={`relative w-full h-full ${
|
||||
punchThrough ? 'bg-transparent' : 'bg-[#0B0D11]'
|
||||
} ${className}`}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
438
src/components/PlayerView.tsx
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
import React, { useState } from 'react';
|
||||
import {
|
||||
PlaySquare,
|
||||
Square,
|
||||
ExternalLink,
|
||||
Maximize2,
|
||||
RefreshCw,
|
||||
Users,
|
||||
MessageSquare,
|
||||
Radio,
|
||||
Tv,
|
||||
Heart,
|
||||
Volume2,
|
||||
VolumeX,
|
||||
ArrowLeftRight,
|
||||
X,
|
||||
Clock,
|
||||
} from 'lucide-react';
|
||||
import { useAppStore } from '../store/appStore';
|
||||
import { tauriApi } from '../lib/tauri';
|
||||
import {
|
||||
computeUptimeSeconds,
|
||||
formatDurationClock,
|
||||
formatUptimeCompact,
|
||||
useNowTick,
|
||||
} from '../lib/time';
|
||||
import { StreamVideo, type StreamLevel } from './StreamVideo';
|
||||
|
||||
interface PlayerViewProps {
|
||||
isMiniPlayer?: boolean;
|
||||
miniCorner?: 'right' | 'left';
|
||||
onToggleMiniCorner?: () => void;
|
||||
}
|
||||
|
||||
export const PlayerView: React.FC<PlayerViewProps> = ({
|
||||
isMiniPlayer = false,
|
||||
miniCorner = 'right',
|
||||
onToggleMiniCorner,
|
||||
}) => {
|
||||
const activeTab = useAppStore((s) => s.activeTab);
|
||||
const activeChannel = useAppStore((s) => s.activeChannel);
|
||||
const activeStream = useAppStore((s) => s.activeStream);
|
||||
const isPlaying = useAppStore((s) => s.isPlaying);
|
||||
const channels = useAppStore((s) => s.channels);
|
||||
const stopPlayback = useAppStore((s) => s.stopPlayback);
|
||||
const playChannel = useAppStore((s) => s.playChannel);
|
||||
const setActiveTab = useAppStore((s) => s.setActiveTab);
|
||||
const toggleChatDrawer = useAppStore((s) => s.toggleChatDrawer);
|
||||
const isChatDrawerOpen = useAppStore((s) => s.isChatDrawerOpen);
|
||||
const isLiveDrawerOpen = useAppStore((s) => s.isLiveDrawerOpen);
|
||||
const toggleLiveDrawer = useAppStore((s) => s.toggleLiveDrawer);
|
||||
const volume = useAppStore((s) => s.volume);
|
||||
const muted = useAppStore((s) => s.muted);
|
||||
const setVolume = useAppStore((s) => s.setVolume);
|
||||
const setMuted = useAppStore((s) => s.setMuted);
|
||||
const isFullscreen = useAppStore((s) => s.isFullscreen);
|
||||
const toggleFullscreen = useAppStore((s) => s.toggleFullscreen);
|
||||
const kickProfile = useAppStore((s) => s.kickProfile);
|
||||
const openKickLogin = useAppStore((s) => s.openKickLogin);
|
||||
const followChannel = useAppStore((s) => s.followChannel);
|
||||
const isUpdateModalOpen = useAppStore((s) => s.isUpdateModalOpen);
|
||||
const [isFollowing, setIsFollowing] = React.useState(false);
|
||||
const [followBusy, setFollowBusy] = React.useState(false);
|
||||
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [levels, setLevels] = useState<StreamLevel[]>([]);
|
||||
const [currentLevel, setCurrentLevel] = useState<number>(-1);
|
||||
|
||||
React.useEffect(() => {
|
||||
setCurrentLevel(-1);
|
||||
setLevels([]);
|
||||
const targetSlug = activeChannel?.channel_name.toLowerCase();
|
||||
if (!targetSlug) {
|
||||
setIsFollowing(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const inLocalList = useAppStore
|
||||
.getState()
|
||||
.channels.some((c) => c.channel_name.toLowerCase() === targetSlug);
|
||||
setIsFollowing(inLocalList);
|
||||
|
||||
let cancelled = false;
|
||||
if (kickProfile && activeChannel) {
|
||||
void tauriApi
|
||||
.kickFollowState(activeChannel.channel_name)
|
||||
.then((state) => {
|
||||
if (!cancelled) setIsFollowing(state);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
let unlisten: (() => void) | undefined;
|
||||
void tauriApi
|
||||
.onKickFollowChanged(({ channel_slug, following }) => {
|
||||
if (!cancelled && channel_slug.toLowerCase() === targetSlug) {
|
||||
setIsFollowing(following);
|
||||
}
|
||||
})
|
||||
.then((fn) => {
|
||||
if (cancelled) fn();
|
||||
else unlisten = fn;
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unlisten?.();
|
||||
};
|
||||
}, [activeChannel?.channel_name, kickProfile]);
|
||||
|
||||
const isLive = activeStream?.is_live ?? activeChannel?.is_live ?? false;
|
||||
|
||||
const handleReload = () => setReloadKey((k) => k + 1);
|
||||
|
||||
const handleToggleFullscreen = () => {
|
||||
void toggleFullscreen();
|
||||
};
|
||||
|
||||
const handleSwitchToExternal = () => {
|
||||
if (activeChannel) playChannel(activeChannel, true);
|
||||
};
|
||||
|
||||
const handleToggleFollow = async () => {
|
||||
if (!activeChannel) return;
|
||||
if (!kickProfile) {
|
||||
void openKickLogin();
|
||||
return;
|
||||
}
|
||||
setFollowBusy(true);
|
||||
try {
|
||||
const next = !isFollowing;
|
||||
const result = await followChannel(
|
||||
activeChannel.channel_name,
|
||||
next,
|
||||
activeChannel.category || undefined
|
||||
);
|
||||
if (result === 'done') {
|
||||
setIsFollowing(next);
|
||||
}
|
||||
} finally {
|
||||
setFollowBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!isPlaying || !activeChannel) {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center bg-[#101318] p-6 text-center select-none">
|
||||
<div className="w-20 h-20 rounded-3xl bg-[#151921] border border-[#2E3542] flex items-center justify-center mb-5 shadow-2xl">
|
||||
<PlaySquare className="w-10 h-10 text-[#60E0B1]/60" />
|
||||
</div>
|
||||
<h2 className="text-lg font-bold text-slate-100">Şu Anda Oynatılan Yayın Yok</h2>
|
||||
<p className="text-xs text-slate-400 max-w-sm mt-2 mb-6">
|
||||
Kanallar sekmesinden canlı yayında olan bir kanala tıklayarak stüdyo oynatıcıda izlemeye
|
||||
başlayabilirsiniz.
|
||||
</p>
|
||||
<button
|
||||
onClick={() => setActiveTab('channels')}
|
||||
className="px-5 py-2.5 rounded-xl bg-gradient-to-r from-[#247553] to-[#4CE0AC] text-[#101318] text-xs font-bold hover:brightness-110 active:scale-95 transition-all flex items-center gap-2 shadow-[0_0_20px_rgba(96,224,177,0.3)]"
|
||||
>
|
||||
<Tv className="w-4 h-4 stroke-[2.5]" />
|
||||
<span>Kanal Listesine Git</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const titleText = activeStream?.title || activeChannel.title || 'Başlık bilgisi yok';
|
||||
const viewersCount = activeStream?.viewers ?? activeChannel.viewers ?? 0;
|
||||
const startedAt = activeStream?.started_at ?? activeChannel.started_at ?? null;
|
||||
const nowMs = useNowTick(isLive && isPlaying && !!activeChannel && !!startedAt, 1000);
|
||||
const uptimeSecs = isLive ? computeUptimeSeconds(startedAt, undefined, nowMs) : 0;
|
||||
const liveChannelsCount = channels.filter((c) => c.is_live).length;
|
||||
|
||||
const showStudioBar = !isMiniPlayer && !isFullscreen;
|
||||
const showVideoSurface = (activeTab === 'player' || isMiniPlayer) && !isUpdateModalOpen;
|
||||
|
||||
return (
|
||||
<div className={isMiniPlayer ? 'w-full flex flex-col bg-[#151921]' : 'flex-1 flex flex-col h-full overflow-hidden bg-transparent'}>
|
||||
{isMiniPlayer && (
|
||||
<div className="h-9 px-2.5 bg-[#151921] border-b border-[#2E3542]/80 flex items-center justify-between gap-2 shrink-0 select-none">
|
||||
<button
|
||||
onClick={() => setActiveTab('player')}
|
||||
title="Oynatıcıyı Büyüt"
|
||||
className="flex items-center gap-2 min-w-0 flex-1 text-left group"
|
||||
>
|
||||
<span className="w-2 h-2 rounded-full bg-[#4CE0AC] animate-pulse shrink-0" />
|
||||
<span className="text-xs font-bold text-slate-100 group-hover:text-[#60E0B1] transition-colors truncate">
|
||||
{activeChannel.channel_name}
|
||||
</span>
|
||||
{isLive && viewersCount > 0 && (
|
||||
<span className="text-[10px] font-medium text-slate-400 shrink-0">
|
||||
· {viewersCount.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
{isLive && uptimeSecs > 0 && (
|
||||
<span
|
||||
title="Canlı yayın süresi"
|
||||
className="text-[10px] font-mono text-[#60E0B1]/90 shrink-0"
|
||||
>
|
||||
· {formatUptimeCompact(uptimeSecs)}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-0.5 shrink-0">
|
||||
<button
|
||||
onClick={() => setMuted(!muted)}
|
||||
title={muted ? 'Sesi Aç' : 'Sessize Al'}
|
||||
className="p-1.5 rounded-lg text-slate-300 hover:text-white hover:bg-[#1B202A] transition-colors"
|
||||
>
|
||||
{muted ? <VolumeX className="w-3.5 h-3.5 text-rose-400" /> : <Volume2 className="w-3.5 h-3.5 text-[#60E0B1]" />}
|
||||
</button>
|
||||
|
||||
{onToggleMiniCorner && (
|
||||
<button
|
||||
onClick={onToggleMiniCorner}
|
||||
title={miniCorner === 'right' ? 'Sol Alt Köşeye Taşı' : 'Sağ Alt Köşeye Taşı'}
|
||||
className="p-1.5 rounded-lg text-slate-300 hover:text-white hover:bg-[#1B202A] transition-colors"
|
||||
>
|
||||
<ArrowLeftRight className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('player')}
|
||||
title="Tam Oynatıcıya Dön"
|
||||
className="p-1.5 rounded-lg text-[#60E0B1] hover:text-white hover:bg-[#247553]/40 transition-colors"
|
||||
>
|
||||
<Maximize2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => void stopPlayback()}
|
||||
title="Yayını Kapat"
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-rose-500/15 transition-colors"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMiniPlayer && (
|
||||
<div
|
||||
className={`h-14 px-4 bg-[#151921] border-b border-[#2E3542]/60 flex items-center justify-between gap-4 z-10 shrink-0 ${
|
||||
!showStudioBar ? 'hidden' : ''
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-[150px] flex-1">
|
||||
<button
|
||||
onClick={() => toggleLiveDrawer()}
|
||||
title="Yayını kesmeden aktif kanallara göz at"
|
||||
className={`px-2.5 py-1.5 rounded-xl border text-xs font-semibold flex items-center gap-1.5 transition-colors shrink-0 ${
|
||||
isLiveDrawerOpen
|
||||
? 'bg-[#247553]/40 text-[#60E0B1] border-[#247553]'
|
||||
: 'bg-[#1B202A] text-slate-300 hover:text-white border-[#2E3542] hover:border-[#60E0B1]/40'
|
||||
}`}
|
||||
>
|
||||
<Radio className="w-3.5 h-3.5 text-[#60E0B1]" />
|
||||
<span className="hidden sm:inline">Canlı Kanallar</span>
|
||||
{liveChannelsCount > 0 && (
|
||||
<span className="px-1.5 py-0.2 rounded-full text-[10px] font-bold bg-[#247553]/50 text-[#60E0B1]">
|
||||
{liveChannelsCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<div className="w-9 h-9 rounded-xl overflow-hidden bg-[#1B202A] border border-[#60E0B1]/50 shrink-0">
|
||||
{activeChannel.avatar_url ? (
|
||||
<img
|
||||
src={activeChannel.avatar_url}
|
||||
alt={activeChannel.channel_name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="w-full h-full flex items-center justify-center text-xs font-bold text-slate-300 uppercase">
|
||||
{activeChannel.channel_name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="text-sm font-bold text-slate-100 truncate min-w-[70px] max-w-[200px]">
|
||||
{activeChannel.channel_name}
|
||||
</h2>
|
||||
{isLive ? (
|
||||
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-bold bg-[#247553]/40 text-[#60E0B1] border border-[#247553]/60">
|
||||
<Radio className="w-2.5 h-2.5 animate-pulse" />
|
||||
CANLI
|
||||
</span>
|
||||
) : (
|
||||
<span className="px-1.5 py-0.5 rounded text-[10px] font-bold bg-[#1B202A] text-slate-400 border border-[#2E3542]">
|
||||
ÇEVRİMDIŞI
|
||||
</span>
|
||||
)}
|
||||
{activeChannel.category && (
|
||||
<span className="hidden lg:inline-block text-[11px] text-slate-400 px-2 py-0.5 rounded bg-[#1B202A] border border-[#2E3542] truncate max-w-[130px]">
|
||||
{activeChannel.category}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-slate-400 truncate max-w-xl">{titleText}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{isLive && uptimeSecs > 0 && (
|
||||
<div
|
||||
title="Canlı yayın süresi"
|
||||
className="hidden sm:flex items-center gap-1.5 px-2.5 py-1 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs font-mono font-semibold text-slate-200 shrink-0"
|
||||
>
|
||||
<Clock className="w-3.5 h-3.5 text-[#60E0B1]" />
|
||||
<span>{formatDurationClock(uptimeSecs)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLive && viewersCount > 0 && (
|
||||
<div className="hidden md:flex items-center gap-1.5 px-2 py-1 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs font-semibold text-slate-300 mr-1 shrink-0">
|
||||
<Users className="w-3.5 h-3.5 text-[#60E0B1]" />
|
||||
<span>{viewersCount.toLocaleString()}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{levels.length > 0 && (
|
||||
<select
|
||||
value={currentLevel}
|
||||
onChange={(e) => setCurrentLevel(Number(e.target.value))}
|
||||
title="Yayın Kalitesi"
|
||||
className="h-8 px-2 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs text-slate-200 focus:outline-none focus:border-[#60E0B1]"
|
||||
>
|
||||
<option value={-1}>Oto Kalite</option>
|
||||
{levels.map((lvl) => (
|
||||
<option key={lvl.index} value={lvl.index}>
|
||||
{lvl.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => void handleToggleFollow()}
|
||||
disabled={followBusy}
|
||||
title={
|
||||
kickProfile
|
||||
? isFollowing
|
||||
? 'Kick hesabından takipten çık'
|
||||
: 'Kick hesabından takip et'
|
||||
: 'Takip etmek için Kick hesabınızla giriş yapın'
|
||||
}
|
||||
className={`p-2 rounded-xl border transition-colors disabled:opacity-50 ${
|
||||
isFollowing
|
||||
? 'bg-rose-500/15 text-rose-300 border-rose-500/40'
|
||||
: 'text-slate-400 hover:text-rose-300 hover:bg-[#1B202A] border-transparent hover:border-[#2E3542]'
|
||||
}`}
|
||||
>
|
||||
<Heart className={`w-4 h-4 ${isFollowing ? 'fill-rose-400' : ''}`} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleReload}
|
||||
title="Yayını Yeniden Yükle"
|
||||
className="p-2 rounded-xl text-slate-400 hover:text-white hover:bg-[#1B202A] border border-transparent hover:border-[#2E3542] transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleSwitchToExternal}
|
||||
title="Harici Oynatıcıya Aktar (VLC/MPV kuruluysa)"
|
||||
className="p-2 rounded-xl text-slate-400 hover:text-[#60E0B1] hover:bg-[#1B202A] border border-transparent hover:border-[#2E3542] transition-colors"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleToggleFullscreen}
|
||||
title={isFullscreen ? 'Tam Ekrandan Çık' : 'Tam Ekran'}
|
||||
className="p-2 rounded-xl text-slate-400 hover:text-white hover:bg-[#1B202A] border border-transparent hover:border-[#2E3542] transition-colors"
|
||||
>
|
||||
<Maximize2 className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => toggleChatDrawer()}
|
||||
title="Sohbet Panelini Aç/Kapat"
|
||||
className={`p-2 rounded-xl border transition-colors ${
|
||||
isChatDrawerOpen
|
||||
? 'bg-[#247553]/40 text-[#60E0B1] border-[#247553]'
|
||||
: 'text-slate-400 hover:text-white hover:bg-[#1B202A] border-transparent hover:border-[#2E3542]'
|
||||
}`}
|
||||
>
|
||||
<MessageSquare className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => stopPlayback()}
|
||||
title="Yayını Durdur"
|
||||
className="p-2 rounded-xl bg-rose-500/10 text-rose-400 hover:bg-rose-500/20 border border-rose-500/30 transition-colors"
|
||||
>
|
||||
<Square className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={
|
||||
isMiniPlayer
|
||||
? 'w-full aspect-video relative overflow-hidden bg-[#0B0D11] cursor-pointer'
|
||||
: 'flex-1 w-full h-full bg-transparent relative overflow-hidden'
|
||||
}
|
||||
>
|
||||
<StreamVideo
|
||||
slotId="main"
|
||||
channelName={activeChannel.channel_name}
|
||||
startedAt={startedAt}
|
||||
level={currentLevel}
|
||||
volume={volume}
|
||||
muted={muted}
|
||||
showControls={!isMiniPlayer}
|
||||
enableShortcuts={activeTab === 'player' && !isMiniPlayer}
|
||||
surfaceVisible={showVideoSurface}
|
||||
aboveParent={isMiniPlayer && !isUpdateModalOpen}
|
||||
onSurfaceClick={isMiniPlayer ? () => setActiveTab('player') : undefined}
|
||||
onToggleFullscreen={handleToggleFullscreen}
|
||||
onToggleMute={() => setMuted(!muted)}
|
||||
onVolumeChange={(value) => setVolume(value)}
|
||||
onToggleChat={!isMiniPlayer ? () => toggleChatDrawer() : undefined}
|
||||
isChatOpen={isChatDrawerOpen}
|
||||
onLevels={(l) => setLevels(l)}
|
||||
reloadToken={reloadKey}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
554
src/components/SettingsView.tsx
Normal file
|
|
@ -0,0 +1,554 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
Settings,
|
||||
Volume2,
|
||||
Bell,
|
||||
PlaySquare,
|
||||
Clock,
|
||||
Save,
|
||||
RotateCcw,
|
||||
ExternalLink,
|
||||
FolderOpen,
|
||||
Monitor,
|
||||
Sparkles,
|
||||
RefreshCw,
|
||||
Copy,
|
||||
Terminal,
|
||||
Target,
|
||||
} from 'lucide-react';
|
||||
import { tauriApi } from '../lib/tauri';
|
||||
import { useAppStore } from '../store/appStore';
|
||||
import type { AppConfig } from '../types';
|
||||
|
||||
export const SettingsView: React.FC = () => {
|
||||
const config = useAppStore((s) => s.config);
|
||||
const saveConfig = useAppStore((s) => s.saveConfig);
|
||||
const addToast = useAppStore((s) => s.addToast);
|
||||
const checkForUpdates = useAppStore((s) => s.checkForUpdates);
|
||||
const updateProgress = useAppStore((s) => s.updateProgress);
|
||||
|
||||
const [form, setForm] = useState<AppConfig | null>(null);
|
||||
const [isPlayingTestSound, setIsPlayingTestSound] = useState(false);
|
||||
const [isCopyingLogs, setIsCopyingLogs] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
setForm({ ...config });
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
if (!form) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center bg-[#101318]">
|
||||
<span className="text-xs text-slate-400 animate-pulse">
|
||||
Ayarlar yükleniyor...
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
await saveConfig(form);
|
||||
};
|
||||
|
||||
const handleTestSound = async () => {
|
||||
try {
|
||||
setIsPlayingTestSound(true);
|
||||
await tauriApi.playTestSound(form.custom_sound_path || undefined, false);
|
||||
setTimeout(() => setIsPlayingTestSound(false), 800);
|
||||
} catch (err: any) {
|
||||
setIsPlayingTestSound(false);
|
||||
addToast({
|
||||
type: 'error',
|
||||
title: 'Ses Çalınamadı',
|
||||
message: err?.toString(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateShortcut = async () => {
|
||||
try {
|
||||
const msg = await tauriApi.createDesktopShortcut();
|
||||
addToast({
|
||||
type: 'success',
|
||||
title: 'Kısayol Oluşturuldu',
|
||||
message: msg,
|
||||
});
|
||||
} catch (err: any) {
|
||||
addToast({
|
||||
type: 'error',
|
||||
title: 'Kısayol Hatası',
|
||||
message: err?.toString(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenLogs = async () => {
|
||||
try {
|
||||
await tauriApi.openLogsDir();
|
||||
} catch (err: any) {
|
||||
addToast({
|
||||
type: 'error',
|
||||
title: 'Klasör Açılamadı',
|
||||
message: err?.toString(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleCopyLogs = async () => {
|
||||
try {
|
||||
setIsCopyingLogs(true);
|
||||
const lines = await tauriApi.getRecentLogs();
|
||||
const report = lines.length > 0 ? lines.join('\n') : 'Henüz kaydedilmiş günlük verisi bulunmuyor.';
|
||||
await navigator.clipboard.writeText(report);
|
||||
setIsCopyingLogs(false);
|
||||
addToast({
|
||||
type: 'success',
|
||||
title: 'Hata Raporu Kopyalandı',
|
||||
message: `${lines.length} satırlık teşhis günlüğü panoya kopyalandı`,
|
||||
});
|
||||
} catch (err: any) {
|
||||
setIsCopyingLogs(false);
|
||||
addToast({
|
||||
type: 'error',
|
||||
title: 'Kopyalanamadı',
|
||||
message: err?.toString(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleReset = async () => {
|
||||
if (confirm('Tüm ayarları varsayılan fabrika ayarlarına sıfırlamak istediğinize emin misiniz?')) {
|
||||
try {
|
||||
const defaultCfg = await tauriApi.resetConfig();
|
||||
setForm({ ...defaultCfg });
|
||||
addToast({
|
||||
type: 'info',
|
||||
title: 'Sıfırlandı',
|
||||
message: 'Tüm ayarlar varsayılana getirildi',
|
||||
});
|
||||
} catch (err: any) {
|
||||
addToast({
|
||||
type: 'error',
|
||||
title: 'Hata',
|
||||
message: err?.toString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col h-full overflow-hidden bg-[#101318] select-none">
|
||||
{/* Settings Header */}
|
||||
<div className="h-14 px-6 bg-[#151921] border-b border-[#2E3542]/50 flex items-center justify-between shrink-0">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<Settings className="w-5 h-5 text-[#60E0B1]" />
|
||||
<div>
|
||||
<h2 className="text-sm font-bold text-slate-100">Uygulama Ayarları</h2>
|
||||
<p className="text-[11px] text-slate-400">
|
||||
Oynatıcı, bildirim, ses ve sistem tercihleri
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="px-4 py-2 rounded-xl bg-gradient-to-r from-[#247553] to-[#4CE0AC] text-[#101318] text-xs font-bold hover:brightness-110 active:scale-95 transition-all shadow-[0_0_15px_rgba(96,224,177,0.3)] flex items-center gap-1.5"
|
||||
>
|
||||
<Save className="w-4 h-4 stroke-[2.5]" />
|
||||
<span>Ayarları Kaydet</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Form Body */}
|
||||
<div className="flex-1 overflow-y-auto p-6 space-y-6 max-w-4xl custom-scrollbar">
|
||||
{/* Section: Oynatıcı Tercihleri */}
|
||||
<section className="bg-[#151921] border border-[#2E3542]/60 rounded-2xl p-5 space-y-4">
|
||||
<h3 className="text-xs font-bold text-slate-200 uppercase tracking-wider flex items-center gap-2">
|
||||
<PlaySquare className="w-4 h-4 text-[#60E0B1]" />
|
||||
Yayın Oynatıcı Seçimi & Kalite
|
||||
</h3>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1.5">
|
||||
Varsayılan Oynatıcı
|
||||
</label>
|
||||
<select
|
||||
value={form.player_type || form.player_choice || 'internal'}
|
||||
onChange={(e) =>
|
||||
setForm({
|
||||
...form,
|
||||
player_type: e.target.value as any,
|
||||
player_choice: e.target.value,
|
||||
})
|
||||
}
|
||||
className="w-full h-10 px-3 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs text-slate-200 focus:outline-none focus:border-[#60E0B1]"
|
||||
>
|
||||
<option value="internal">Uygulama İçi Native Oynatıcı (libmpv D3D11VA)</option>
|
||||
<option value="vlc">VLC Media Player (Harici)</option>
|
||||
<option value="mpv">MPV Player (Harici)</option>
|
||||
<option value="streamlink">Streamlink CLI</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1.5">
|
||||
Varsayılan Kalite
|
||||
</label>
|
||||
<select
|
||||
value={form.default_quality || form.stream_quality || 'best'}
|
||||
onChange={(e) =>
|
||||
setForm({
|
||||
...form,
|
||||
default_quality: e.target.value,
|
||||
stream_quality: e.target.value,
|
||||
})
|
||||
}
|
||||
className="w-full h-10 px-3 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs text-slate-200 focus:outline-none focus:border-[#60E0B1]"
|
||||
>
|
||||
<option value="best">En Yüksek (1080p60 / Kaynak)</option>
|
||||
<option value="720p60">720p 60 FPS</option>
|
||||
<option value="720p">720p HD</option>
|
||||
<option value="480p">480p</option>
|
||||
<option value="360p">360p</option>
|
||||
<option value="worst">En Düşük (Düşük Bant Genişliği)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-3 pt-2">
|
||||
<div>
|
||||
<label className="block text-[11px] font-medium text-slate-400 mb-1">
|
||||
Özel VLC Yolu (İsteğe Bağlı)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="C:\Program Files\VideoLAN\VLC\vlc.exe"
|
||||
value={form.vlc_path || ''}
|
||||
onChange={(e) => setForm({ ...form, vlc_path: e.target.value })}
|
||||
className="w-full h-9 px-3 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs text-slate-200 focus:outline-none focus:border-[#60E0B1]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-[11px] font-medium text-slate-400 mb-1">
|
||||
Özel MPV Yolu (İsteğe Bağlı)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="C:\Program Files\mpv\mpv.exe"
|
||||
value={form.mpv_path || ''}
|
||||
onChange={(e) => setForm({ ...form, mpv_path: e.target.value })}
|
||||
className="w-full h-9 px-3 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs text-slate-200 focus:outline-none focus:border-[#60E0B1]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-[11px] font-medium text-slate-400 mb-1">
|
||||
Özel Streamlink Yolu (İsteğe Bağlı)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="C:\Program Files\Streamlink\bin\streamlink.exe"
|
||||
value={form.streamlink_path || ''}
|
||||
onChange={(e) => setForm({ ...form, streamlink_path: e.target.value })}
|
||||
className="w-full h-9 px-3 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs text-slate-200 focus:outline-none focus:border-[#60E0B1]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Custom player arguments */}
|
||||
<div className="pt-2">
|
||||
<label className="block text-[11px] font-medium text-slate-300 mb-1 flex items-center gap-1.5">
|
||||
<Terminal className="w-3.5 h-3.5 text-[#60E0B1]" />
|
||||
<span>Ek Oynatıcı Argümanları (VLC / MPV / Streamlink)</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="ör. --network-caching=1000 --hwdec=auto"
|
||||
value={form.custom_player_args || ''}
|
||||
onChange={(e) => setForm({ ...form, custom_player_args: e.target.value })}
|
||||
className="w-full h-9 px-3 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs text-slate-200 focus:outline-none focus:border-[#60E0B1] font-mono"
|
||||
/>
|
||||
<span className="text-[10px] text-slate-500 mt-1 block">
|
||||
Harici oynatıcı başlatılırken eklenecek güvenli komut satırı parametreleri.
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Section: Yoklama & Yenileme */}
|
||||
<section className="bg-[#151921] border border-[#2E3542]/60 rounded-2xl p-5 space-y-4">
|
||||
<h3 className="text-xs font-bold text-slate-200 uppercase tracking-wider flex items-center gap-2">
|
||||
<Clock className="w-4 h-4 text-[#60E0B1]" />
|
||||
Arka Plan Yoklama & Yenileme
|
||||
</h3>
|
||||
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="max-w-md">
|
||||
<span className="text-xs font-semibold text-slate-200 block">
|
||||
Otomatik Canlı Yayın Kontrolü Aralığı
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-400">
|
||||
Kick API'den favori kanalların durumunu otomatik kontrol etme sıklığı.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<input
|
||||
type="number"
|
||||
min={15}
|
||||
max={300}
|
||||
value={form.refresh_interval_seconds}
|
||||
onChange={(e) =>
|
||||
setForm({
|
||||
...form,
|
||||
refresh_interval_seconds: Math.max(15, parseInt(e.target.value) || 60),
|
||||
})
|
||||
}
|
||||
className="w-20 h-10 px-3 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs text-center font-bold text-[#60E0B1] focus:outline-none focus:border-[#60E0B1]"
|
||||
/>
|
||||
<span className="text-xs text-slate-400">saniye</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Section: Bildirimler ve Sesler */}
|
||||
<section className="bg-[#151921] border border-[#2E3542]/60 rounded-2xl p-5 space-y-4">
|
||||
<h3 className="text-xs font-bold text-slate-200 uppercase tracking-wider flex items-center gap-2">
|
||||
<Bell className="w-4 h-4 text-[#60E0B1]" />
|
||||
Canlı Bildirimleri & Ses Uyarıları
|
||||
</h3>
|
||||
|
||||
<div className="space-y-3">
|
||||
{/* Desktop Notifications Toggle */}
|
||||
<label className="flex items-center justify-between p-3 rounded-xl bg-[#1B202A]/60 hover:bg-[#1B202A] transition-colors cursor-pointer">
|
||||
<div>
|
||||
<span className="text-xs font-semibold text-slate-200 block">
|
||||
Windows Masaüstü Bildirimleri
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-400">
|
||||
Takip ettiğiniz bir yayıncı canlı yayına başladığında sistem bildirimi göster.
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.notifications_enabled}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, notifications_enabled: e.target.checked })
|
||||
}
|
||||
className="w-4 h-4 rounded text-[#60E0B1] accent-[#60E0B1] cursor-pointer"
|
||||
/>
|
||||
</label>
|
||||
|
||||
{/* Notify on category change */}
|
||||
<label className="flex items-center justify-between p-3 rounded-xl bg-[#1B202A]/60 hover:bg-[#1B202A] transition-colors cursor-pointer">
|
||||
<div>
|
||||
<span className="text-xs font-semibold text-slate-200 block">
|
||||
Kategori Değişiklik Bildirimi
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-400">
|
||||
Yayındaki kanal oyun veya kategori değiştirdiğinde haber ver.
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.notify_on_category_change ?? false}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, notify_on_category_change: e.target.checked })
|
||||
}
|
||||
className="w-4 h-4 rounded text-[#60E0B1] accent-[#60E0B1] cursor-pointer"
|
||||
/>
|
||||
</label>
|
||||
|
||||
{/* Keyword alerts */}
|
||||
<div className="p-3 rounded-xl bg-[#1B202A]/60 space-y-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Target className="w-3.5 h-3.5 text-[#60E0B1]" />
|
||||
<span className="text-xs font-semibold text-slate-200">
|
||||
Özel Anahtar Kelime Uyarıları (Hedef Takibi)
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-[11px] text-slate-400 block">
|
||||
Yayın başlığında veya kategorisinde geçtiğinde acil bildirim tetiklenecek kelimeler (virgülle ayırın):
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="ör. çekiliş, turnuva, drop, giveaway"
|
||||
value={form.alert_keywords || ''}
|
||||
onChange={(e) => setForm({ ...form, alert_keywords: e.target.value })}
|
||||
className="w-full h-9 px-3 rounded-xl bg-[#13161C] border border-[#2E3542] text-xs text-slate-200 focus:outline-none focus:border-[#60E0B1]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sound Notifications Toggle */}
|
||||
<label className="flex items-center justify-between p-3 rounded-xl bg-[#1B202A]/60 hover:bg-[#1B202A] transition-colors cursor-pointer">
|
||||
<div>
|
||||
<span className="text-xs font-semibold text-slate-200 block">
|
||||
Sesli Uyarı Çal
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-400">
|
||||
Yayın başladığında yumuşak çift tonlu polifonik melodi çal.
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.sound_notifications_enabled ?? form.sound_enabled ?? true}
|
||||
onChange={(e) =>
|
||||
setForm({
|
||||
...form,
|
||||
sound_notifications_enabled: e.target.checked,
|
||||
sound_enabled: e.target.checked,
|
||||
})
|
||||
}
|
||||
className="w-4 h-4 rounded text-[#60E0B1] accent-[#60E0B1] cursor-pointer"
|
||||
/>
|
||||
</label>
|
||||
|
||||
{/* Test sound button */}
|
||||
<div className="flex items-center justify-between pt-1">
|
||||
<div>
|
||||
<span className="text-xs font-medium text-slate-300 block">
|
||||
Özel Ses Dosyası (WAV / MP3)
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-500">
|
||||
Boş bırakılırsa LD KickWatch çift tonlu sentez sesi kullanılır.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleTestSound}
|
||||
disabled={isPlayingTestSound}
|
||||
className="px-3 py-1.5 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs font-medium text-slate-300 hover:text-[#60E0B1] hover:border-[#60E0B1]/50 transition-colors flex items-center gap-1.5"
|
||||
>
|
||||
<Volume2 className={`w-3.5 h-3.5 ${isPlayingTestSound ? 'text-[#60E0B1] animate-bounce' : ''}`} />
|
||||
<span>Test Sesi Çal</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Section: Otomatik Güncelleme (Self-Hosted OTA) */}
|
||||
<section className="bg-[#151921] border border-[#2E3542]/60 rounded-2xl p-5 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-xs font-bold text-slate-200 uppercase tracking-wider flex items-center gap-2">
|
||||
<Sparkles className="w-4 h-4 text-[#60E0B1]" />
|
||||
Otomatik Güncelleme (OTA) & Sürüm
|
||||
</h3>
|
||||
<span className="text-[11px] font-mono px-2 py-0.5 rounded-full bg-[#1B202A] border border-[#2E3542] text-zinc-400">
|
||||
Mevcut Sürüm: <strong className="text-[#60E0B1]">v2.6.12</strong>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 pt-1">
|
||||
<label className="flex items-center justify-between cursor-pointer p-3 rounded-xl bg-[#101318]/60 border border-[#2E3542]/40 hover:border-[#60E0B1]/30 transition-all">
|
||||
<div>
|
||||
<span className="text-xs font-semibold text-slate-200 block">
|
||||
Uygulama Açılırken Otomatik Güncelle
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-400">
|
||||
Uygulama başladığında sessizce yeni sürümü kontrol eder. Yeni sürüm varsa otomatik olarak indirip günceller.
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.auto_update_on_startup ?? true}
|
||||
onChange={(e) =>
|
||||
setForm({
|
||||
...form,
|
||||
auto_update_on_startup: e.target.checked,
|
||||
})
|
||||
}
|
||||
className="w-4 h-4 rounded text-[#60E0B1] accent-[#60E0B1] cursor-pointer"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 pt-2">
|
||||
<div className="text-[11px] text-slate-500">
|
||||
Güncellemeler doğrudan <span className="font-mono text-zinc-400">ttmadethat.shop</span> sunucusundan şifrelenmiş Minisign imzasıyla indirilir.
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => checkForUpdates(true)}
|
||||
disabled={updateProgress.status === 'checking'}
|
||||
className="px-4 py-2 rounded-xl bg-[#247553] hover:bg-[#2e8f66] border border-[#60E0B1]/40 text-xs font-semibold text-[#60E0B1] hover:text-white transition-all flex items-center gap-2 shadow-sm active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${updateProgress.status === 'checking' ? 'animate-spin' : ''}`} />
|
||||
<span>{updateProgress.status === 'checking' ? 'Kontrol Ediliyor...' : 'Güncellemeleri Şimdi Kontrol Et'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Section: Sistem & Kısayollar */}
|
||||
<section className="bg-[#151921] border border-[#2E3542]/60 rounded-2xl p-5 space-y-4">
|
||||
<h3 className="text-xs font-bold text-slate-200 uppercase tracking-wider flex items-center gap-2">
|
||||
<Monitor className="w-4 h-4 text-[#60E0B1]" />
|
||||
Sistem Entegrasyonu, Günlükler & Araçlar
|
||||
</h3>
|
||||
|
||||
<label className="flex items-center justify-between p-3 rounded-xl bg-[#1B202A]/60 hover:bg-[#1B202A] transition-colors cursor-pointer">
|
||||
<div>
|
||||
<span className="text-xs font-semibold text-slate-200 block">
|
||||
Kapatınca Sistem Tepsisine Küçült
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-400">
|
||||
Açıkken kapat (X) tuşu uygulamayı tamamen kapatmak yerine sağ alt sistem tepsisine gizler.
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.minimize_to_tray ?? false}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, minimize_to_tray: e.target.checked })
|
||||
}
|
||||
className="w-4 h-4 rounded text-[#60E0B1] accent-[#60E0B1] cursor-pointer"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCreateShortcut}
|
||||
className="px-4 py-2 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs font-semibold text-slate-200 hover:text-[#60E0B1] hover:border-[#60E0B1]/50 transition-all flex items-center gap-2"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4 text-[#60E0B1]" />
|
||||
<span>Masaüstü Kısayolu Oluştur</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleOpenLogs}
|
||||
className="px-4 py-2 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs font-semibold text-slate-200 hover:text-white hover:border-slate-500 transition-all flex items-center gap-2"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4 text-amber-400" />
|
||||
<span>Log Klasörünü Aç</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopyLogs}
|
||||
disabled={isCopyingLogs}
|
||||
className="px-4 py-2 rounded-xl bg-[#1B202A] border border-[#2E3542] text-xs font-semibold text-slate-200 hover:text-[#60E0B1] hover:border-[#60E0B1]/50 transition-all flex items-center gap-2"
|
||||
>
|
||||
<Copy className="w-4 h-4 text-[#60E0B1]" />
|
||||
<span>{isCopyingLogs ? 'Alınıyor...' : 'Hata Raporunu Kopyala'}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleReset}
|
||||
className="px-4 py-2 rounded-xl bg-rose-500/10 border border-rose-500/30 text-xs font-semibold text-rose-400 hover:bg-rose-500/20 transition-all flex items-center gap-2 ml-auto"
|
||||
>
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
<span>Varsayılana Sıfırla</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
262
src/components/Sidebar.tsx
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
import React, { useMemo, useState } from 'react';
|
||||
import {
|
||||
Tv,
|
||||
PlaySquare,
|
||||
LayoutGrid,
|
||||
Radio,
|
||||
RefreshCw,
|
||||
Settings,
|
||||
Info,
|
||||
LogIn,
|
||||
LogOut,
|
||||
UserRound,
|
||||
ArrowDownToLine,
|
||||
} from 'lucide-react';
|
||||
import { useAppStore } from '../store/appStore';
|
||||
import type { ActiveTab } from '../types';
|
||||
|
||||
export const Sidebar: React.FC = () => {
|
||||
const activeTab = useAppStore((s) => s.activeTab);
|
||||
const setActiveTab = useAppStore((s) => s.setActiveTab);
|
||||
const isLiveDrawerOpen = useAppStore((s) => s.isLiveDrawerOpen);
|
||||
const toggleLiveDrawer = useAppStore((s) => s.toggleLiveDrawer);
|
||||
const refreshChannels = useAppStore((s) => s.refreshChannels);
|
||||
const isLoadingChannels = useAppStore((s) => s.isLoadingChannels);
|
||||
const channels = useAppStore((s) => s.channels);
|
||||
const activeChannel = useAppStore((s) => s.activeChannel);
|
||||
const playChannel = useAppStore((s) => s.playChannel);
|
||||
const liveChannels = useMemo(
|
||||
() =>
|
||||
channels
|
||||
.filter((c) => c.is_live)
|
||||
.sort((a, b) => (b.viewers || 0) - (a.viewers || 0)),
|
||||
[channels]
|
||||
);
|
||||
const liveCount = liveChannels.length;
|
||||
const kickProfile = useAppStore((s) => s.kickProfile);
|
||||
const kickBusy = useAppStore((s) => s.kickBusy);
|
||||
const openKickLogin = useAppStore((s) => s.openKickLogin);
|
||||
const logoutKick = useAppStore((s) => s.logoutKick);
|
||||
const syncKickFollows = useAppStore((s) => s.syncKickFollows);
|
||||
const [accountMenuOpen, setAccountMenuOpen] = useState(false);
|
||||
|
||||
const navItems: { tab: ActiveTab; label: string; icon: React.ReactNode }[] = [
|
||||
{
|
||||
tab: 'channels',
|
||||
label: 'TR Top 12 (Anlık En Çok İzlenenler)',
|
||||
icon: <Tv className="w-5 h-5" />,
|
||||
},
|
||||
{
|
||||
tab: 'player',
|
||||
label: 'Oynatıcı',
|
||||
icon: <PlaySquare className="w-5 h-5" />,
|
||||
},
|
||||
{
|
||||
tab: 'squad',
|
||||
label: 'Çoklu İzleme (2x2)',
|
||||
icon: <LayoutGrid className="w-5 h-5" />,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<aside className="w-16 bg-[#101318] border-r border-[#2E3542]/50 flex flex-col items-center py-3 justify-between select-none z-40 shrink-0">
|
||||
{/* Top Nav Buttons */}
|
||||
<div className="flex flex-col items-center gap-2 w-full px-2 shrink-0">
|
||||
{/* Primary Highlight: Aktif Takip Edilenler Side Panel Toggle (Always Top) */}
|
||||
<div className="w-full flex flex-col items-center pb-2.5 mb-0.5 border-b border-[#2E3542]/60">
|
||||
<button
|
||||
onClick={() => toggleLiveDrawer()}
|
||||
title="Aktif Takip Edilenler Panelini Aç / Kapat"
|
||||
className={`relative w-12 h-12 rounded-2xl flex items-center justify-center transition-all duration-200 ${
|
||||
isLiveDrawerOpen
|
||||
? 'bg-gradient-to-br from-[#247553] via-[#1C5C41] to-[#132920] text-[#60E0B1] border border-[#60E0B1]/70 shadow-[0_0_20px_rgba(96,224,177,0.32)] ring-1 ring-[#60E0B1]/25'
|
||||
: 'bg-[#151921] text-slate-300 hover:text-[#60E0B1] border border-[#2E3542] hover:border-[#60E0B1]/50 hover:bg-[#1B202A]'
|
||||
}`}
|
||||
>
|
||||
<Radio className={`w-5 h-5 ${liveCount > 0 ? 'animate-pulse text-[#60E0B1]' : ''}`} />
|
||||
{liveCount > 0 && (
|
||||
<span className="absolute -top-1.5 -right-1.5 min-w-[20px] px-1.5 py-0.5 text-[10px] font-extrabold rounded-full bg-gradient-to-r from-[#247553] to-[#4CE0AC] text-[#0B0E13] shadow-[0_2px_8px_rgba(76,224,172,0.5)] leading-none text-center">
|
||||
{liveCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{navItems.map((item) => {
|
||||
const isActive = activeTab === item.tab;
|
||||
return (
|
||||
<button
|
||||
key={item.tab}
|
||||
onClick={() => setActiveTab(item.tab)}
|
||||
title={item.label}
|
||||
className={`relative w-12 h-12 rounded-xl flex items-center justify-center transition-all duration-200 group ${
|
||||
isActive
|
||||
? 'bg-[#151921] text-[#60E0B1] shadow-[0_0_15px_rgba(96,224,177,0.2)] border border-[#247553]/60'
|
||||
: 'text-slate-400 hover:text-slate-200 hover:bg-[#1B202A]/80'
|
||||
}`}
|
||||
>
|
||||
{item.icon}
|
||||
|
||||
{/* Indicator bar */}
|
||||
{isActive && (
|
||||
<div className="absolute left-0 top-2.5 bottom-2.5 w-1 bg-[#60E0B1] rounded-r-full" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Collapsed Quick Live Streamer Tiles (shown between divider lines only when drawer is closed) */}
|
||||
{!isLiveDrawerOpen && (
|
||||
<div className="flex-1 min-h-0 w-full my-2 py-2 border-y border-[#2E3542]/70 overflow-y-auto no-scrollbar flex flex-col items-center gap-2 px-2">
|
||||
{liveChannels.map((ch) => {
|
||||
const isCurrent =
|
||||
activeChannel?.channel_name.toLowerCase() === ch.channel_name.toLowerCase();
|
||||
return (
|
||||
<button
|
||||
key={ch.channel_name}
|
||||
onClick={() => void playChannel(ch)}
|
||||
title={`${ch.channel_name}${ch.category ? ` · ${ch.category}` : ''} (${(ch.viewers || 0).toLocaleString('tr-TR')})`}
|
||||
className="w-12 shrink-0 flex flex-col items-center gap-1 group"
|
||||
>
|
||||
<div className="relative w-11 h-11 shrink-0">
|
||||
<div
|
||||
className={`w-full h-full rounded-xl overflow-hidden border-2 bg-[#1B202A] flex items-center justify-center transition-all duration-150 ${
|
||||
isCurrent
|
||||
? 'border-[#60E0B1] shadow-[0_0_12px_rgba(96,224,177,0.35)]'
|
||||
: 'border-[#247553]/70 group-hover:border-[#60E0B1]'
|
||||
}`}
|
||||
>
|
||||
{ch.avatar_url ? (
|
||||
<img
|
||||
src={ch.avatar_url}
|
||||
alt={ch.channel_name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-xs font-bold uppercase text-slate-300">
|
||||
{ch.channel_name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-[#4CE0AC] border-2 border-[#101318]" />
|
||||
</div>
|
||||
<span
|
||||
className={`w-full text-[9px] font-bold leading-tight truncate text-center transition-colors ${
|
||||
isCurrent
|
||||
? 'text-[#60E0B1]'
|
||||
: 'text-slate-300 group-hover:text-[#60E0B1]'
|
||||
}`}
|
||||
>
|
||||
{ch.channel_name}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Bottom Nav Buttons */}
|
||||
<div className="flex flex-col items-center gap-2 w-full px-2 shrink-0">
|
||||
{/* Kick account: login button or avatar + account menu */}
|
||||
<div className="relative">
|
||||
{kickProfile ? (
|
||||
<button
|
||||
onClick={() => setAccountMenuOpen((open) => !open)}
|
||||
title={`${kickProfile.username} · Kick hesabı`}
|
||||
className="w-11 h-11 rounded-xl overflow-hidden border border-[#247553]/70 ring-1 ring-[#60E0B1]/30 flex items-center justify-center bg-[#1B202A] hover:border-[#60E0B1] transition-all"
|
||||
>
|
||||
{kickProfile.avatar_url ? (
|
||||
<img
|
||||
src={kickProfile.avatar_url}
|
||||
alt={kickProfile.username}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<UserRound className="w-5 h-5 text-[#60E0B1]" />
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => openKickLogin()}
|
||||
title="Kick ile Giriş Yap"
|
||||
className="w-12 h-12 rounded-xl flex items-center justify-center text-slate-400 hover:text-[#60E0B1] hover:bg-[#1B202A]/80 transition-all"
|
||||
>
|
||||
<LogIn className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{accountMenuOpen && kickProfile && (
|
||||
<div className="absolute bottom-0 left-14 w-60 rounded-xl bg-[#151921] border border-[#2E3542] shadow-2xl p-2 z-50">
|
||||
<div className="px-2 py-1.5 border-b border-[#2E3542]/60 mb-1">
|
||||
<p className="text-xs font-bold text-slate-100 truncate">
|
||||
{kickProfile.username}
|
||||
</p>
|
||||
<p className="text-[10px] text-[#60E0B1]">Kick hesabı bağlı</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setAccountMenuOpen(false);
|
||||
void syncKickFollows();
|
||||
}}
|
||||
disabled={kickBusy}
|
||||
className="w-full flex items-center gap-2 px-2 py-2 rounded-lg text-xs text-slate-200 hover:bg-[#1B202A] disabled:opacity-50 transition-colors"
|
||||
>
|
||||
<ArrowDownToLine className="w-4 h-4 text-[#60E0B1]" />
|
||||
Takip Edilenleri Senkronize Et
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setAccountMenuOpen(false);
|
||||
void logoutKick();
|
||||
}}
|
||||
className="w-full flex items-center gap-2 px-2 py-2 rounded-lg text-xs text-rose-300 hover:bg-rose-500/10 transition-colors"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
Çıkış Yap
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Refresh Button */}
|
||||
<button
|
||||
onClick={() => refreshChannels()}
|
||||
disabled={isLoadingChannels}
|
||||
title="Kanalları Yenile (F5)"
|
||||
className="w-12 h-12 rounded-xl flex items-center justify-center text-slate-400 hover:text-slate-200 hover:bg-[#1B202A]/80 transition-all duration-200 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-5 h-5 ${isLoadingChannels ? 'animate-spin text-[#60E0B1]' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{/* Settings Button */}
|
||||
<button
|
||||
onClick={() => setActiveTab('settings')}
|
||||
title="Ayarlar"
|
||||
className={`w-12 h-12 rounded-xl flex items-center justify-center transition-all duration-200 ${
|
||||
activeTab === 'settings'
|
||||
? 'bg-[#151921] text-[#60E0B1] border border-[#247553]/60'
|
||||
: 'text-slate-400 hover:text-slate-200 hover:bg-[#1B202A]/80'
|
||||
}`}
|
||||
>
|
||||
<Settings className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
{/* About Button */}
|
||||
<button
|
||||
onClick={() => setActiveTab('about')}
|
||||
title="Hakkında"
|
||||
className={`w-12 h-12 rounded-xl flex items-center justify-center transition-all duration-200 ${
|
||||
activeTab === 'about'
|
||||
? 'bg-[#151921] text-[#60E0B1] border border-[#247553]/60'
|
||||
: 'text-slate-400 hover:text-slate-200 hover:bg-[#1B202A]/80'
|
||||
}`}
|
||||
>
|
||||
<Info className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
280
src/components/SquadView.tsx
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
import React, { useState } from 'react';
|
||||
import {
|
||||
Volume2,
|
||||
VolumeX,
|
||||
X,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Sparkles,
|
||||
LayoutGrid,
|
||||
Radio,
|
||||
} from 'lucide-react';
|
||||
import { useAppStore } from '../store/appStore';
|
||||
import { StreamVideo } from './StreamVideo';
|
||||
|
||||
export const SquadView: React.FC = () => {
|
||||
const squadSlots = useAppStore((s) => s.squadSlots);
|
||||
const setSquadSlot = useAppStore((s) => s.setSquadSlot);
|
||||
const clearSquadSlot = useAppStore((s) => s.clearSquadSlot);
|
||||
const activeSquadAudioIndex = useAppStore((s) => s.activeSquadAudioIndex);
|
||||
const setActiveSquadAudioIndex = useAppStore((s) => s.setActiveSquadAudioIndex);
|
||||
const channels = useAppStore((s) => s.channels);
|
||||
const volume = useAppStore((s) => s.volume);
|
||||
const globalMuted = useAppStore((s) => s.muted);
|
||||
const isUpdateModalOpen = useAppStore((s) => s.isUpdateModalOpen);
|
||||
const liveChannels = channels.filter((c) => c.is_live);
|
||||
|
||||
const [slotToSelect, setSlotToSelect] = useState<number | null>(null);
|
||||
const [showAllPicker, setShowAllPicker] = useState(false);
|
||||
const [reloadKeys, setReloadKeys] = useState<number[]>([0, 0, 0, 0]);
|
||||
|
||||
const pickerChannels = showAllPicker || liveChannels.length === 0 ? channels : liveChannels;
|
||||
|
||||
const handleReloadSlot = (index: number) => {
|
||||
setReloadKeys((prev) => {
|
||||
const next = [...prev];
|
||||
next[index] = next[index] + 1;
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleAutoFill = () => {
|
||||
liveChannels.slice(0, 4).forEach((ch, idx) => {
|
||||
setSquadSlot(idx, ch.channel_name);
|
||||
});
|
||||
};
|
||||
|
||||
const handleClearAll = () => {
|
||||
for (let i = 0; i < 4; i++) {
|
||||
clearSquadSlot(i);
|
||||
}
|
||||
};
|
||||
|
||||
const hasAnySlot = squadSlots.some(Boolean);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex-1 flex flex-col h-full overflow-hidden ${
|
||||
hasAnySlot ? 'bg-transparent' : 'bg-[#101318]'
|
||||
}`}
|
||||
>
|
||||
{/* Top Toolbar (Opaque) */}
|
||||
<div className="h-12 px-4 bg-[#151921] border-b border-[#2E3542]/50 flex items-center justify-between gap-4 z-10 shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<LayoutGrid className="w-4 h-4 text-[#60E0B1]" />
|
||||
<h2 className="text-xs font-bold text-slate-100 tracking-wide uppercase">
|
||||
Çoklu İzleme Stüdyosu (2x2 Squad)
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{liveChannels.length > 0 && (
|
||||
<button
|
||||
onClick={handleAutoFill}
|
||||
className="px-3 py-1.5 rounded-lg bg-[#247553]/40 text-[#60E0B1] border border-[#247553]/60 text-xs font-medium hover:bg-[#247553] hover:text-white transition-colors flex items-center gap-1.5"
|
||||
title="Canlı kanallarla otomatik doldur"
|
||||
>
|
||||
<Sparkles className="w-3.5 h-3.5" />
|
||||
<span>Canlıları Otomatik Yerleştir</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleClearAll}
|
||||
className="px-3 py-1.5 rounded-lg bg-[#1B202A] text-slate-400 border border-[#2E3542] text-xs font-medium hover:text-rose-400 hover:border-rose-500/40 transition-colors"
|
||||
>
|
||||
Tümünü Temizle
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 2x2 Grid Viewport (Opaque outer borders prevent desktop bleed-through between tiles) */}
|
||||
<div
|
||||
className={`flex-1 grid grid-cols-2 grid-rows-2 gap-0 p-0 overflow-hidden ${
|
||||
hasAnySlot ? 'bg-transparent' : 'bg-[#0C0E12]'
|
||||
}`}
|
||||
>
|
||||
{squadSlots.map((slotChannel, index) => {
|
||||
const isAudioActive = activeSquadAudioIndex === index;
|
||||
const channelInfo = channels.find(
|
||||
(c) => c.channel_name.toLowerCase() === slotChannel.toLowerCase()
|
||||
);
|
||||
|
||||
if (!slotChannel) {
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className="h-full w-full border-4 border-[#0C0E12] bg-[#0C0E12]"
|
||||
>
|
||||
<div
|
||||
className="h-full w-full rounded-xl bg-[#13161C] border border-dashed border-[#2E3542] flex flex-col items-center justify-center p-4 text-center hover:border-[#60E0B1]/50 hover:bg-[#151921] transition-all group cursor-pointer"
|
||||
onClick={() => setSlotToSelect(index)}
|
||||
>
|
||||
<div className="w-12 h-12 rounded-xl bg-[#1B202A] border border-[#2E3542] group-hover:border-[#60E0B1] group-hover:scale-105 flex items-center justify-center mb-3 transition-all">
|
||||
<Plus className="w-6 h-6 text-slate-400 group-hover:text-[#60E0B1]" />
|
||||
</div>
|
||||
<span className="text-xs font-semibold text-slate-300 group-hover:text-slate-100">
|
||||
{index + 1}. Ekranı Ayarla
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-500 mt-1">
|
||||
Kanal seçmek için tıklayın
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
onClick={() => setActiveSquadAudioIndex(index)}
|
||||
title={isAudioActive ? 'Ses bu ekranda' : 'Sesi bu ekrana vermek için tıkla'}
|
||||
className="relative h-full w-full border-4 border-[#0C0E12] overflow-hidden bg-transparent cursor-pointer"
|
||||
>
|
||||
{/* Active audio indicator frame over transparent viewport */}
|
||||
<div
|
||||
className={`pointer-events-none absolute inset-0 z-10 border transition-colors ${
|
||||
isAudioActive
|
||||
? 'border-[#60E0B1] shadow-[inset_0_0_16px_rgba(96,224,177,0.25)]'
|
||||
: 'border-[#2E3542]/70'
|
||||
}`}
|
||||
/>
|
||||
|
||||
{/* Overlay Header Controls */}
|
||||
<div
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="absolute top-0 inset-x-0 h-9 bg-gradient-to-b from-black/80 via-black/40 to-transparent flex items-center justify-between px-3 z-20 pointer-events-auto"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-bold text-white drop-shadow">
|
||||
{slotChannel}
|
||||
</span>
|
||||
{channelInfo?.is_live && (
|
||||
<span className="flex items-center gap-1 text-[9px] font-bold text-[#60E0B1] px-1 rounded bg-black/60">
|
||||
<Radio className="w-2 h-2" />
|
||||
CANLI
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => setActiveSquadAudioIndex(index)}
|
||||
title={isAudioActive ? 'Ses Açık (Odakta)' : 'Sesi Bu Ekrana Ver'}
|
||||
className={`p-1 rounded-md transition-colors ${
|
||||
isAudioActive
|
||||
? 'bg-[#247553] text-[#60E0B1]'
|
||||
: 'bg-black/60 text-slate-300 hover:text-white hover:bg-black/90'
|
||||
}`}
|
||||
>
|
||||
{isAudioActive ? (
|
||||
<Volume2 className="w-3.5 h-3.5" />
|
||||
) : (
|
||||
<VolumeX className="w-3.5 h-3.5 text-slate-400" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleReloadSlot(index)}
|
||||
title="Yenile"
|
||||
className="p-1 rounded-md bg-black/60 text-slate-300 hover:text-white hover:bg-black/90 transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => clearSquadSlot(index)}
|
||||
title="Kaldır"
|
||||
className="p-1 rounded-md bg-black/60 text-slate-300 hover:text-rose-400 hover:bg-black/90 transition-colors"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Native libmpv player slot */}
|
||||
<StreamVideo
|
||||
slotId={`squad-${index}`}
|
||||
channelName={slotChannel}
|
||||
muted={globalMuted || !isAudioActive}
|
||||
volume={volume}
|
||||
showControls={false}
|
||||
surfaceVisible={!isUpdateModalOpen}
|
||||
reloadToken={reloadKeys[index]}
|
||||
className="w-full h-full"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Select Channel Modal */}
|
||||
{slotToSelect !== null && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4">
|
||||
<div className="w-full max-w-sm bg-[#151921] border border-[#2E3542] rounded-2xl p-5 shadow-2xl animate-in fade-in zoom-in-95 duration-150">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-sm font-bold text-slate-100">
|
||||
{slotToSelect + 1}. Ekrana Kanal Seç
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => setSlotToSelect(null)}
|
||||
className="text-slate-400 hover:text-white"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 max-h-60 overflow-y-auto custom-scrollbar pr-1">
|
||||
{pickerChannels.map((ch) => (
|
||||
<button
|
||||
key={ch.channel_name}
|
||||
onClick={() => {
|
||||
setSquadSlot(slotToSelect, ch.channel_name);
|
||||
setSlotToSelect(null);
|
||||
}}
|
||||
className="w-full flex items-center justify-between p-2.5 rounded-xl hover:bg-[#1B202A] border border-transparent hover:border-[#2E3542] transition-colors text-left"
|
||||
>
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<div className="w-7 h-7 rounded-lg overflow-hidden bg-[#101318] shrink-0 border border-[#2E3542]">
|
||||
{ch.avatar_url ? (
|
||||
<img
|
||||
src={ch.avatar_url}
|
||||
alt={ch.channel_name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="w-full h-full flex items-center justify-center text-[10px] font-bold text-slate-400 uppercase">
|
||||
{ch.channel_name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs font-semibold text-slate-200 truncate">
|
||||
{ch.channel_name}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{ch.is_live && (
|
||||
<span className="text-[10px] font-bold text-[#60E0B1] bg-[#247553]/40 px-1.5 py-0.5 rounded border border-[#247553]/60">
|
||||
CANLI
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{liveChannels.length > 0 && channels.length > liveChannels.length && (
|
||||
<button
|
||||
onClick={() => setShowAllPicker((v) => !v)}
|
||||
className="mt-3 w-full text-[11px] font-semibold text-slate-400 hover:text-[#60E0B1] transition-colors"
|
||||
>
|
||||
{showAllPicker
|
||||
? `Yalnızca canlıları göster (${liveChannels.length})`
|
||||
: `Tüm kanalları göster (${channels.length})`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||