chore: add bilingual documentation, MIT license, and clean repository for Forgejo
30
.gitignore
vendored
|
|
@ -1,6 +1,31 @@
|
||||||
|
# Tauri & Node
|
||||||
|
node_modules/
|
||||||
|
src-tauri/target/
|
||||||
|
|
||||||
|
# Security, Private Credentials & Local Server Scripts (NEVER commit)
|
||||||
|
.keys/
|
||||||
|
*.key
|
||||||
|
*.sig
|
||||||
|
*.pem
|
||||||
|
*.pfx
|
||||||
|
*.p12
|
||||||
|
bağlan.bat
|
||||||
|
*baglan*.bat
|
||||||
|
ba*lan.bat
|
||||||
|
*.bat.backup
|
||||||
|
publish.ps1
|
||||||
|
publish.bat
|
||||||
|
release.ps1
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
secrets.*
|
||||||
|
config.local.*
|
||||||
|
|
||||||
# PyInstaller & Build outputs
|
# PyInstaller & Build outputs
|
||||||
build/
|
build/
|
||||||
dist/
|
dist/
|
||||||
|
dist-updates/
|
||||||
|
|
||||||
# Python temporary and cache files
|
# Python temporary and cache files
|
||||||
__pycache__/
|
__pycache__/
|
||||||
|
|
@ -9,11 +34,14 @@ __pycache__/
|
||||||
*.pyd
|
*.pyd
|
||||||
|
|
||||||
# Runtime logs and cookies
|
# Runtime logs and cookies
|
||||||
|
*.log
|
||||||
temp.txt
|
temp.txt
|
||||||
cookies.txt
|
cookies.txt
|
||||||
github-recovery-codes.txt
|
github-recovery-codes.txt
|
||||||
|
|
||||||
# OS specific files
|
# Editor & OS specific files
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
|
|
|
||||||
164
README.md
|
|
@ -1,130 +1,86 @@
|
||||||
# LDownloader v3.5.0 🎬🎵
|
<div align="center">
|
||||||
|
|
||||||
[](LICENSE)
|
<img src="assets/logo.png" width="96" alt="LDownloader Logo" />
|
||||||
[](https://github.com/LilDosto/LDownloader/releases)
|
|
||||||
|
|
||||||
**LDownloader**, Python, Tkinter ve `yt-dlp` tabanlı, koyu temalı bir Windows masaüstü video ve ses indirme uygulamasıdır. Kullanılabilir platformlar ve formatlar, kaynak içeriğe ve `yt-dlp` desteğine bağlıdır.
|
# LDownloader
|
||||||
|
|
||||||

|
**Windows için Tauri v2 ve Rust tabanlı hızlı medya ve Kick.com indiricisi • Ultra-fast Windows media & Kick.com downloader built with Tauri v2 and Rust**
|
||||||
|
|
||||||
|
[](./LICENSE)
|
||||||
|
[](https://git.ttmadethat.shop/LilDosto/LDownloader/releases/latest)
|
||||||
|
[](https://v2.tauri.app)
|
||||||
|
[](https://git.ttmadethat.shop/LilDosto/LDownloader/releases/latest)
|
||||||
|
|
||||||
|
[🇹🇷 Türkçe](#-türkçe) • [🇬🇧 English](#-english) • [📦 Releases](https://git.ttmadethat.shop/LilDosto/LDownloader/releases/latest)
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ✨ Öne Çıkan Özellikler
|
## 🇹🇷 Türkçe
|
||||||
|
|
||||||
### 1. 🔍 Akıllı Video Önizleme & Dinamik Çözünürlük Tespiti
|
**LDownloader**, Tauri v2, Rust arka ucu ve React 18 / TypeScript arayüzüyle geliştirilmiş; tekli video/ses, oynatma listesi, toplu URL indirme ve Kick.com yayın/VOD/klip indirme özelliklerini bir arada sunan hafif bir Windows medya indiricisidir.
|
||||||
* Bir video bağlantısı yapıştırıldığında arka planda video başlığı, yayıncı kanal adı, video süresi ve kapak resmi (thumbnail) otomatik olarak çekilir.
|
|
||||||
* Sabit çözünürlük tahminleri yerine, videoda **gerçekte bulunan tüm çözünürlük seçenekleri** (4K, 2K, 1080p, 720p vb.) algılanıp seçim menüsüne eklenir.
|
|
||||||
|
|
||||||
### 2. ⚡ 1-Tıkla Otomatik FFmpeg & yt-dlp Kurucusu
|
### Özellikler
|
||||||
* Sisteminizde `ffmpeg` veya `yt-dlp` yoksa **Ayarlar** sekmesinden bunları indirebilirsiniz.
|
|
||||||
* İndirilen araçlar uygulamanın kullanıcı veri klasöründeki `bin/` dizinine kaydedilir; Windows PATH ayarını değiştirmeniz gerekmez. İndirme için internet bağlantısı gerekir.
|
|
||||||
|
|
||||||
### 3. 📦 Toplu İndirme (Batch Downloader)
|
- **Çoklu İndirme Modları:** Tekli URL, Oynatma Listesi (Playlist), Toplu Liste (Batch), Kick.com kanalı/yayını, İndirme Geçmişi ve Ayarlar sekmeleri.
|
||||||
* İndirmek istediğiniz birden çok video veya ses bağlantısını alt alta yapıştırın.
|
- **Kick Canlı Yayın, VOD & Klipler:** Yayıncı adına göre canlı yayın durumu, VOD tekrarları ve popüler klipleri tarama; canlı yayını anlık MP4 olarak kaydetme.
|
||||||
* Sıralı indirme kuyruğu her bir öğenin durumunu (Bekliyor / İndiriliyor / Tamamlandı / Hata) anlık olarak takip eder.
|
- **Akıllı Video Analizi & İndirme Seçenekleri:** Yapıştırılan bağlantılar için başlık, kapak, süre ve çözünürlüklerin hızlı önizlemesi; altyazı gömme, kapak/meta veri ekleme, çok parçalı indirme ve SponsorBlock segment atlama desteği.
|
||||||
|
- **Güvenlik Dayanıklılığı:** `yt-dlp` argüman enjeksiyonu koruması (`--` ayracı ve `http/https` protokol doğrulaması), indirilen çalıştırılabilir dosyaların otomatik yürütülmesini engelleyen güvenli dosya açma, izole `%APPDATA%/LDownloader/bin` bağımlılık yönetimi (`yt-dlp`, `ffmpeg`) ve bozuk JSON ayar/geçmiş dosyaları için otomatik yedekli kurtarma.
|
||||||
|
- **OTA Güncelleme & Tanılama:** Tekil uygulama örneği, sistem tepsisi, Minisign imzalı self-hosted OTA güncelleme, tek tıkla sistem tanılama raporu ve log klasörü erişimi.
|
||||||
|
|
||||||
### 4. 🕒 İndirme Geçmişi & Dosya Yöneticisi
|
### Teknoloji Yığını
|
||||||
* Tekil ve toplu indirme kayıtları tarih, dosya boyutu ve format bilgisiyle yerel olarak saklanır. Oynatma listesi işlemi şu anda tek bir geçmiş kaydı oluşturur.
|
|
||||||
* 📁 **Klasörde Göster**: Windows Gezgini'ni açıp doğrudan dosyayı seçili olarak görüntüler (`explorer /select`).
|
|
||||||
* ▶ **Oynat / Aç**: Varsayılan medya oynatıcınızda videoyu veya müziği anında başlatır.
|
|
||||||
|
|
||||||
### 5. 🚀 Çok Parçalı İndirme
|
- **Masaüstü & Çekirdek:** Tauri v2 (`tauri 2.2`), Rust (`tokio`, `reqwest`, `zip`, `regex`, `windows-sys`), `yt-dlp` + `ffmpeg`
|
||||||
* İsteğe bağlı çok parçalı indirme, desteklenen akışlarda indirme hızını artırabilir. Gerçek performans ağınıza ve kaynak platforma bağlıdır; belirli bir hız artışı garanti edilmez.
|
- **Arayüz:** React 18, TypeScript, Tailwind CSS, Zustand, Lucide Icons, Vite
|
||||||
|
|
||||||
### 6. 💬 Altyazı & 🖼️ Kapak Resmi Gömme
|
### Kurulum ve Kullanım
|
||||||
* **Altyazı Desteği**: İstenirse Türkçe ve İngilizce altyazılar indirilip, FFmpeg'in desteklediği durumlarda videoya gömülür.
|
|
||||||
* **Kapak Resmi ve Metadata**: İsteğe bağlı olarak kapak görseli ve metadata, desteklenen formatlara eklenir.
|
|
||||||
|
|
||||||
### 7. 🍪 Zen Browser & Modern Çerez (Cookies) Yönetimi
|
**Son Kullanıcı:**
|
||||||
* **Önemli Çerez Bildirimi**: YouTube oturum çerezleri en fazla **30 dakikada bir** yenilenmelidir. Windows App-Bound güvenlik koruması sebebiyle Chromium tabanlı tarayıcılardan (Chrome, Edge, Brave vb.) doğrudan otomatik çerez çekimi kısıtlıdır; Firefox, Zen Browser veya `cookies.txt` eklentisi önerilir.
|
1. [Releases](https://git.ttmadethat.shop/LilDosto/LDownloader/releases/latest) sayfasından `LDownloader_3.6.0_x64-setup.exe` dosyasını indirip kurun.
|
||||||
* Yaş kısıtlamalı, gizli veya YouTube 403 engeline takılan videolarda oturum çerezlerinizi tek tıkla aktarın:
|
2. İlk açılışta **Ayarlar** sekmesinden gerekli bağımlılıkların (`yt-dlp` ve `ffmpeg`) durumunu kontrol edip tek tıkla kurabilirsiniz.
|
||||||
* **Desteklenen tarayıcı seçenekleri**: Zen Browser, Firefox, Chrome, Microsoft Edge, Brave, Opera, Vivaldi, Chromium.
|
|
||||||
* İsteğe bağlı manuel `cookies.txt` yükleme desteği.
|
|
||||||
|
|
||||||
### 8. 📋 Gelişmiş Playlist İndirme
|
**Geliştirici (Kaynaktan Derleme):**
|
||||||
* Oynatma listelerini sıralı klasör yapısıyla (`Playlist Adı / 01 - Video.mp4`) kaydeder.
|
```powershell
|
||||||
* Başlangıç ve bitiş indeks aralığı belirleyebilir, hatalı/gizli videoları atlayarak indirmeye devam edebilirsiniz.
|
npm install
|
||||||
|
npm run tauri dev # Geliştirme modunda çalıştır
|
||||||
### 9. 🟢 Kick Canlı Yayın, VOD & Clips İndirici
|
npm run tauri build # Üretim kurulum paketini derle
|
||||||
* **Kanal Tarayıcısı (Keşif Modu)**: Sadece yayıncının kanal adını (örn: `elraenn`, `xqc`) yazarak kanalın canlı yayın durumunu, tüm geçmiş yayınlarını (**VOD**) ve popüler kliplerini (**Clips**) uygulama içinden listeleyebilirsiniz.
|
|
||||||
* **Canlı Yayın Kaydedici**: Devam eden canlı yayınları gerçek zamanlı olarak kaydeder, yayını baştan alma (DVR) ve çevrimdışı yayıncının yayına girmesini otomatik bekleme seçenekleri sunar.
|
|
||||||
* **VOD Kesit Alma**: Saatler süren yayın tekrarlarının tamamını indirmek yerine yalnızca istediğiniz zaman aralığını (örn: `00:10:00` - `00:25:30`) kesip indirebilirsiniz.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📁 Proje Mimarisi
|
|
||||||
|
|
||||||
```
|
|
||||||
LDownloader/
|
|
||||||
├── core/ # İş mantığı ve arka plan motorları
|
|
||||||
│ ├── config.py # Kalıcı kullanıcı ayarları (config.json)
|
|
||||||
│ ├── dependencies.py # yt-dlp & FFmpeg algılama, 1-tıkla indirme/kurma
|
|
||||||
│ ├── downloader.py # Asenkron indirme motoru ve süreç ağacı yönetimi
|
|
||||||
│ ├── metadata.py # Hızlı video önizleme, thumbnail ve format ayrıştırıcı
|
|
||||||
│ ├── diagnostics.py # Akıllı Türkçe hata teşhisi ve çözüm motoru
|
|
||||||
│ └── history.py # İndirme geçmişi (history.json)
|
|
||||||
├── ui/ # Arayüz bileşenleri ve modern tasarım
|
|
||||||
│ ├── theme.py # SaaS koyu mod renk paleti ve stilleri
|
|
||||||
│ ├── components.py # Modern kartlar, butonlar, giriş alanları, önizleme kartı
|
|
||||||
│ ├── tabs/
|
|
||||||
│ │ ├── single_tab.py # Önizlemeli tekil indirme sekmesi
|
|
||||||
│ │ ├── playlist_tab.py # Oynatma listesi sekmesi
|
|
||||||
│ │ ├── batch_tab.py # Toplu indirme sekmesi
|
|
||||||
│ │ ├── history_tab.py # İndirme geçmişi sekmesi
|
|
||||||
│ │ └── settings_tab.py # Ayarlar, çerezler ve bağımlılık yöneticisi
|
|
||||||
│ └── app.py # Ana pencere ve sekme orkestrasyonu
|
|
||||||
├── assets/ # Görsel ikonlar (logo.ico, logo.png)
|
|
||||||
├── main.py # Ana uygulama başlatıcısı
|
|
||||||
├── ytdlp_indirici.spec # PyInstaller derleme yapılandırması
|
|
||||||
├── build_exe.bat # Tek tıkla Windows EXE derleme aracı
|
|
||||||
├── requirements.txt # Python bağımlılıkları
|
|
||||||
└── README.md # Dokümantasyon
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🚀 Kurulum ve Çalıştırma
|
## 🇬🇧 English
|
||||||
|
|
||||||
### Gizlilik ve kullanım
|
**LDownloader** is an ultra-lightweight Windows desktop media and Kick.com downloader built with Tauri v2, Rust, and React 18 / TypeScript, supporting single downloads, playlists, batch queues, and Kick live/VOD/clip capture.
|
||||||
* Çerezler hesabınıza erişim sağlayabilir. Yalnızca kendi hesabınızın çerezlerini kullanın; çerez dosyalarını veya uygulama tanılama kayıtlarını başkalarıyla paylaşmayın.
|
|
||||||
* İndirilen içerikleri kullanırken ilgili platformların hizmet koşullarına, içerik sahiplerinin haklarına ve yerel mevzuata uyun. Uygulama, bir içeriği indirme veya yeniden kullanma hakkı vermez.
|
|
||||||
* Harici araçlar ve medya içeriği internetten indirilir. İndirme ve kurulum işlemleri güvenilir bir ağ üzerinden yapılmalıdır.
|
|
||||||
|
|
||||||
### 1. Gereksinimleri Yükleyin:
|
### Features
|
||||||
```bash
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Uygulamayı Başlatın:
|
- **Multi-Mode Downloader:** Dedicated views for Single URL, Playlist, Batch queue, Kick.com streams, Download History, and Settings.
|
||||||
```bash
|
- **Kick Live Streams, VODs & Clips:** Browse channels by name for live status, VOD replays, and top clips, or record live streams directly to MP4.
|
||||||
python main.py
|
- **Smart Metadata Preview & Options:** Instant inspection of title, thumbnail, duration, and available resolutions; supports subtitle embedding, thumbnail/metadata tagging, multi-connection downloading, and SponsorBlock skipping.
|
||||||
|
- **Security Hardening:** `yt-dlp` CLI argument-injection protection (`--` delimiter + `http/https` URL validation), safe file opening (blocks launching downloaded executables), isolated `%APPDATA%/LDownloader/bin` dependency loading (`yt-dlp`, `ffmpeg`), and self-healing config/history JSON backup recovery.
|
||||||
|
- **OTA Updates & Diagnostics:** Single-instance guard, system tray, Minisign-verified OTA updater, one-click diagnostics report, and log folder access.
|
||||||
|
|
||||||
|
### Tech Stack
|
||||||
|
|
||||||
|
- **Desktop & Backend:** Tauri v2 (`tauri 2.2`), Rust (`tokio`, `reqwest`, `zip`, `regex`, `windows-sys`), `yt-dlp` + `ffmpeg`
|
||||||
|
- **Frontend:** React 18, TypeScript, Tailwind CSS, Zustand, Lucide Icons, Vite
|
||||||
|
|
||||||
|
### Installation & Usage
|
||||||
|
|
||||||
|
**End Users:**
|
||||||
|
1. Download `LDownloader_3.6.0_x64-setup.exe` from [Releases](https://git.ttmadethat.shop/LilDosto/LDownloader/releases/latest) and run the installer.
|
||||||
|
2. On first launch, verify or install `yt-dlp` and `ffmpeg` directly from the **Settings** tab.
|
||||||
|
|
||||||
|
**Developers (Build from Source):**
|
||||||
|
```powershell
|
||||||
|
npm install
|
||||||
|
npm run tauri dev # Run in development mode
|
||||||
|
npm run tauri build # Build Windows installer
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📦 İndirme ve Kurulum
|
## 📄 Lisans / License
|
||||||
|
|
||||||
LDownloader'ı iki farklı şekilde kullanabilirsiniz:
|
Bu proje [MIT Lisansı](./LICENSE) altında lisanslanmıştır. • Licensed under the [MIT License](./LICENSE).
|
||||||
|
|
||||||
1. **Kurulum Sihirbazı (Önerilen - `LDownloader-Setup.exe`):**
|
|
||||||
* Standart bir Windows programı gibi adım adım kurulur.
|
|
||||||
* Masaüstüne ve Başlat Menüsüne otomatik kısayol oluşturur.
|
|
||||||
* Windows Ayarları -> Yüklü Uygulamalar (Program Ekle/Kaldır) üzerinden güvenle kaldırılabilir.
|
|
||||||
2. **Taşınabilir Sürüm (Portable - `LDownloader.exe`):**
|
|
||||||
* Kurulum gerektirmeden indirip doğrudan çift tıklayarak çalıştırabilirsiniz.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🛠️ Tek Tıkla EXE ve Kurulum Sihirbazı Derleme
|
|
||||||
|
|
||||||
Uygulamayı ve kurulum sihirbazını yerel olarak derlemek için:
|
|
||||||
* `build_exe.bat` dosyasına çift tıklayın veya çalıştırın:
|
|
||||||
* Derleme sonucunda `dist/` klasöründe hem taşınabilir `LDownloader.exe` hem de `LDownloader-v3.5.0-Setup.exe` üretilecektir.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📝 Lisans ve Katkı
|
|
||||||
|
|
||||||
Bu proje [MIT Lisansı](LICENSE) altında lisanslanmıştır. Özgürce kullanabilir, değiştirebilir ve dağıtabilirsiniz. Hata bildirimleri veya yeni özellik önerileri için Pull Request gönderebilir veya Issue oluşturabilirsiniz.
|
|
||||||
|
|
||||||
İyi indirmeler! 🚀
|
|
||||||
|
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
@echo off
|
|
||||||
chcp 65001 >nul
|
|
||||||
echo ===================================================
|
|
||||||
echo LDownloader v3.3.0 - Windows EXE & Kurulum Sihirbazi
|
|
||||||
echo ===================================================
|
|
||||||
echo.
|
|
||||||
|
|
||||||
python -m PyInstaller --noconfirm ytdlp_indirici.spec
|
|
||||||
if %ERRORLEVEL% NEQ 0 (
|
|
||||||
echo.
|
|
||||||
echo [HATA] Derleme basarisiz oldu. PyInstaller kurulu oldugundan emin olun:
|
|
||||||
echo pip install -r requirements.txt
|
|
||||||
pause
|
|
||||||
exit /b 1
|
|
||||||
)
|
|
||||||
|
|
||||||
echo.
|
|
||||||
if exist build rmdir /s /q build
|
|
||||||
echo [BASARILI] dist\LDownloader.exe basariyla olusturuldu!
|
|
||||||
|
|
||||||
set "ISCC_PATH=%LOCALAPPDATA%\Programs\Inno Setup 6\ISCC.exe"
|
|
||||||
if not exist "%ISCC_PATH%" set "ISCC_PATH=C:\Program Files (x86)\Inno Setup 6\ISCC.exe"
|
|
||||||
if not exist "%ISCC_PATH%" set "ISCC_PATH=C:\Program Files\Inno Setup 6\ISCC.exe"
|
|
||||||
|
|
||||||
if exist "%ISCC_PATH%" (
|
|
||||||
echo.
|
|
||||||
echo Kurulum Sihirbazi (Setup.exe) derleniyor...
|
|
||||||
"%ISCC_PATH%" installer.iss
|
|
||||||
if %ERRORLEVEL% EQU 0 (
|
|
||||||
echo [BASARILI] Kurulum dosyasi dist\LDownloader-v3.3.0-Setup.exe olusturuldu!
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
echo.
|
|
||||||
echo Islem tamamlandi!
|
|
||||||
pause
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
"""LDownloader Core Modules"""
|
|
||||||
108
core/config.py
|
|
@ -1,108 +0,0 @@
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
def get_app_dir():
|
|
||||||
"""PyInstaller veya kaynak kod dizini."""
|
|
||||||
if getattr(sys, 'frozen', False):
|
|
||||||
return getattr(sys, '_MEIPASS', os.path.dirname(sys.executable))
|
|
||||||
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
|
||||||
def get_data_dir():
|
|
||||||
"""Kullanıcı verilerinin ve ayarların saklandığı dizin."""
|
|
||||||
app_data = os.getenv('APPDATA')
|
|
||||||
if app_data:
|
|
||||||
data_dir = os.path.join(app_data, 'LDownloader')
|
|
||||||
else:
|
|
||||||
data_dir = os.path.join(os.path.expanduser('~'), '.ldownloader')
|
|
||||||
os.makedirs(data_dir, exist_ok=True)
|
|
||||||
return data_dir
|
|
||||||
|
|
||||||
def get_bin_dir():
|
|
||||||
"""Taşınabilir yt-dlp.exe ve ffmpeg.exe ikililerinin saklandığı dizin."""
|
|
||||||
# Öncelik 1: Uygulama çalışma dizinindeki bin/ (yazılabilirse veya içinde araç varsa)
|
|
||||||
local_bin = os.path.join(get_app_dir(), 'bin')
|
|
||||||
if os.path.isdir(local_bin) and os.access(local_bin, os.W_OK):
|
|
||||||
return local_bin
|
|
||||||
|
|
||||||
# Öncelik 2: AppData altındaki bin/
|
|
||||||
user_bin = os.path.join(get_data_dir(), 'bin')
|
|
||||||
os.makedirs(user_bin, exist_ok=True)
|
|
||||||
return user_bin
|
|
||||||
|
|
||||||
|
|
||||||
class ConfigManager:
|
|
||||||
_DEFAULT_CONFIG = {
|
|
||||||
"theme": "dark",
|
|
||||||
"download_dir": os.path.join(os.path.expanduser("~"), "Downloads"),
|
|
||||||
"video_format": "mp4",
|
|
||||||
"video_quality": "Best Quality (En İyi)",
|
|
||||||
"audio_format": "mp3",
|
|
||||||
"audio_quality": "Best Quality (En İyi)",
|
|
||||||
"cookies_mode": "none",
|
|
||||||
"cookies_browser": "chrome",
|
|
||||||
"cookies_path": "",
|
|
||||||
"embed_subtitles": False,
|
|
||||||
"subtitle_lang": "tr,en",
|
|
||||||
"embed_thumbnail": True,
|
|
||||||
"add_metadata": True,
|
|
||||||
"concurrent_fragments": 4,
|
|
||||||
"auto_fetch_metadata": True,
|
|
||||||
"speed_limit": "",
|
|
||||||
"proxy": "",
|
|
||||||
"ignore_errors": True,
|
|
||||||
"use_download_archive": False,
|
|
||||||
"sponsorblock_remove": False,
|
|
||||||
"sponsorblock_cats": "sponsor,intro,outro,selfpromo,interaction"
|
|
||||||
}
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.config_path = os.path.join(get_data_dir(), "config.json")
|
|
||||||
self.config = dict(self._DEFAULT_CONFIG)
|
|
||||||
self.load()
|
|
||||||
|
|
||||||
def load(self):
|
|
||||||
if os.path.exists(self.config_path):
|
|
||||||
try:
|
|
||||||
with open(self.config_path, "r", encoding="utf-8") as f:
|
|
||||||
saved = json.load(f)
|
|
||||||
if not isinstance(saved, dict):
|
|
||||||
raise ValueError("Config file must contain a JSON object.")
|
|
||||||
if "concurrent_fragments" in saved:
|
|
||||||
try:
|
|
||||||
fragments = int(saved["concurrent_fragments"])
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
fragments = self._DEFAULT_CONFIG["concurrent_fragments"]
|
|
||||||
if fragments not in (1, 2, 4, 8, 16):
|
|
||||||
fragments = self._DEFAULT_CONFIG["concurrent_fragments"]
|
|
||||||
saved["concurrent_fragments"] = fragments
|
|
||||||
self.config.update(saved)
|
|
||||||
except (OSError, json.JSONDecodeError, ValueError):
|
|
||||||
logger.exception("Could not load configuration from %s", self.config_path)
|
|
||||||
|
|
||||||
def save(self):
|
|
||||||
temp_path = self.config_path + ".tmp"
|
|
||||||
try:
|
|
||||||
with open(temp_path, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(self.config, f, indent=4, ensure_ascii=False)
|
|
||||||
f.flush()
|
|
||||||
os.replace(temp_path, self.config_path)
|
|
||||||
except OSError:
|
|
||||||
logger.exception("Could not save configuration to %s", self.config_path)
|
|
||||||
try:
|
|
||||||
os.remove(temp_path)
|
|
||||||
except OSError:
|
|
||||||
logger.debug("Could not remove temporary configuration file %s", temp_path, exc_info=True)
|
|
||||||
|
|
||||||
def get(self, key, default=None):
|
|
||||||
return self.config.get(key, default if default is not None else self._DEFAULT_CONFIG.get(key))
|
|
||||||
|
|
||||||
def set(self, key, value):
|
|
||||||
self.config[key] = value
|
|
||||||
self.save()
|
|
||||||
|
|
||||||
# Tekil örnek
|
|
||||||
config = ConfigManager()
|
|
||||||
|
|
@ -1,297 +0,0 @@
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import shutil
|
|
||||||
import zipfile
|
|
||||||
import subprocess
|
|
||||||
import configparser
|
|
||||||
import requests
|
|
||||||
import time
|
|
||||||
from core.config import get_bin_dir, get_app_dir, get_data_dir
|
|
||||||
|
|
||||||
# bin/ dizinini çalışma zamanı PATH değişkeninin başına ekle
|
|
||||||
_bin_dir = get_bin_dir()
|
|
||||||
if _bin_dir and _bin_dir not in os.environ.get("PATH", ""):
|
|
||||||
os.environ["PATH"] = f"{_bin_dir}{os.pathsep}{os.environ.get('PATH', '')}"
|
|
||||||
|
|
||||||
def get_ytdlp_cmd():
|
|
||||||
"""yt-dlp çalıştırma komutunu liste olarak döndürür (exe veya python -m yt_dlp)."""
|
|
||||||
exe = find_executable("yt-dlp")
|
|
||||||
if exe:
|
|
||||||
return [exe]
|
|
||||||
if not getattr(sys, "frozen", False):
|
|
||||||
try:
|
|
||||||
import yt_dlp # noqa: F401
|
|
||||||
return [sys.executable, "-m", "yt_dlp"]
|
|
||||||
except ImportError:
|
|
||||||
pass
|
|
||||||
return ["yt-dlp"]
|
|
||||||
|
|
||||||
def find_executable(name: str):
|
|
||||||
"""Belirtilen çalıştırılabilir dosyayı bin/ klasöründe veya PATH'te arar."""
|
|
||||||
exe_name = f"{name}.exe" if sys.platform == "win32" else name
|
|
||||||
|
|
||||||
# 1. User AppData bin dizinini kontrol et
|
|
||||||
user_bin = os.path.join(get_data_dir(), "bin", exe_name)
|
|
||||||
if os.path.isfile(user_bin) and os.access(user_bin, os.X_OK):
|
|
||||||
return user_bin
|
|
||||||
|
|
||||||
# 2. Local / Aktif bin dizinini kontrol et
|
|
||||||
bin_dir = get_bin_dir()
|
|
||||||
local_path = os.path.join(bin_dir, exe_name)
|
|
||||||
if os.path.isfile(local_path) and os.access(local_path, os.X_OK):
|
|
||||||
return local_path
|
|
||||||
|
|
||||||
# 3. PyInstaller _MEIPASS veya app dizinindeki bin klasörü
|
|
||||||
app_bin = os.path.join(get_app_dir(), "bin", exe_name)
|
|
||||||
if os.path.isfile(app_bin):
|
|
||||||
return app_bin
|
|
||||||
|
|
||||||
# 4. Python Scripts dizini kontrolü (örn: yt-dlp pip ile kurulmuşsa)
|
|
||||||
python_dir = os.path.dirname(sys.executable)
|
|
||||||
py_script = os.path.join(python_dir, "Scripts", exe_name)
|
|
||||||
if os.path.isfile(py_script):
|
|
||||||
return py_script
|
|
||||||
|
|
||||||
# 5. Windows Programs Python Scripts kontrolü
|
|
||||||
if sys.platform == "win32":
|
|
||||||
local_appdata = os.getenv("LOCALAPPDATA", "")
|
|
||||||
py_programs = os.path.join(local_appdata, "Programs", "Python")
|
|
||||||
if os.path.isdir(py_programs):
|
|
||||||
for entry in os.listdir(py_programs):
|
|
||||||
candidate = os.path.join(py_programs, entry, "Scripts", exe_name)
|
|
||||||
if os.path.isfile(candidate):
|
|
||||||
return candidate
|
|
||||||
|
|
||||||
# 6. Sistem PATH kontrolü
|
|
||||||
return shutil.which(name)
|
|
||||||
|
|
||||||
|
|
||||||
def get_ytdlp_status():
|
|
||||||
"""yt-dlp durumunu (kurulu_mu, versiyon, yol) döndürür."""
|
|
||||||
exe = find_executable("yt-dlp")
|
|
||||||
if not exe:
|
|
||||||
# pip modülü veya PyInstaller gömülü modül kontrolü
|
|
||||||
try:
|
|
||||||
import yt_dlp
|
|
||||||
import yt_dlp.version
|
|
||||||
ver = getattr(yt_dlp.version, "__version__", "Gömülü")
|
|
||||||
return True, str(ver), "embedded"
|
|
||||||
except Exception:
|
|
||||||
return False, "Bulunamadı", None
|
|
||||||
|
|
||||||
try:
|
|
||||||
flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
|
||||||
out = subprocess.check_output([exe, "--version"], text=True, stderr=subprocess.STDOUT, creationflags=flags)
|
|
||||||
return True, out.strip(), exe
|
|
||||||
except Exception:
|
|
||||||
return True, "Mevcut", exe
|
|
||||||
|
|
||||||
|
|
||||||
def get_ffmpeg_status():
|
|
||||||
"""ffmpeg durumunu (kurulu_mu, versiyon, yol) döndürür."""
|
|
||||||
exe = find_executable("ffmpeg")
|
|
||||||
if not exe:
|
|
||||||
return False, "Bulunamadı", None
|
|
||||||
try:
|
|
||||||
flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
|
||||||
out = subprocess.check_output([exe, "-version"], text=True, stderr=subprocess.STDOUT, creationflags=flags)
|
|
||||||
first_line = out.splitlines()[0] if out else "Mevcut"
|
|
||||||
return True, first_line[:30], exe
|
|
||||||
except Exception:
|
|
||||||
return True, "Mevcut", exe
|
|
||||||
|
|
||||||
|
|
||||||
def get_js_status():
|
|
||||||
"""YouTube n-challenge/EJS için JS motoru durumunu döndürür."""
|
|
||||||
for js in ("deno", "node", "qjs"):
|
|
||||||
exe = find_executable(js)
|
|
||||||
if exe:
|
|
||||||
return True, f"Hazır ({js.capitalize()})", exe
|
|
||||||
return False, "Bulunamadı", None
|
|
||||||
|
|
||||||
|
|
||||||
def get_ffmpeg_dir():
|
|
||||||
"""Eğer ffmpeg yerel bin dizinindeyse dizin yolunu döndürür (--ffmpeg-location için)."""
|
|
||||||
exe = find_executable("ffmpeg")
|
|
||||||
if exe:
|
|
||||||
return os.path.dirname(exe)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def install_deno(progress_callback=None):
|
|
||||||
"""YouTube EJS challenge çözümleri için resmi Deno motorunu indirir."""
|
|
||||||
bin_dir = get_bin_dir()
|
|
||||||
os.makedirs(bin_dir, exist_ok=True)
|
|
||||||
zip_path = os.path.join(bin_dir, "deno_download.zip")
|
|
||||||
url = "https://github.com/denoland/deno/releases/download/v2.9.6/deno-x86_64-pc-windows-msvc.zip"
|
|
||||||
download_file_with_progress(url, zip_path, progress_callback)
|
|
||||||
with zipfile.ZipFile(zip_path, 'r') as zf:
|
|
||||||
zf.extract("deno.exe", bin_dir)
|
|
||||||
try:
|
|
||||||
os.remove(zip_path)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return os.path.join(bin_dir, "deno.exe")
|
|
||||||
|
|
||||||
|
|
||||||
def download_file_with_progress(url: str, dest_path: str, progress_callback=None):
|
|
||||||
"""URL'den dosyayı indirir ve ilerlemeyi bildirir."""
|
|
||||||
response = requests.get(url, stream=True, timeout=30)
|
|
||||||
response.raise_for_status()
|
|
||||||
total_length = response.headers.get('content-length')
|
|
||||||
|
|
||||||
downloaded = 0
|
|
||||||
total = int(total_length) if total_length else None
|
|
||||||
last_callback_time = 0.0
|
|
||||||
|
|
||||||
with open(dest_path, "wb") as f:
|
|
||||||
for chunk in response.iter_content(chunk_size=1024 * 64):
|
|
||||||
if chunk:
|
|
||||||
f.write(chunk)
|
|
||||||
downloaded += len(chunk)
|
|
||||||
if progress_callback and total:
|
|
||||||
now = time.monotonic()
|
|
||||||
pct = (downloaded / total) * 100
|
|
||||||
if (now - last_callback_time >= 0.08) or pct >= 100:
|
|
||||||
last_callback_time = now
|
|
||||||
progress_callback(pct, downloaded, total)
|
|
||||||
|
|
||||||
|
|
||||||
def install_ytdlp(progress_callback=None):
|
|
||||||
"""Resmi GitHub yayınından en güncel yt-dlp.exe dosyasını indirir."""
|
|
||||||
bin_dir = get_bin_dir()
|
|
||||||
os.makedirs(bin_dir, exist_ok=True)
|
|
||||||
target = os.path.join(bin_dir, "yt-dlp.exe")
|
|
||||||
url = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe"
|
|
||||||
|
|
||||||
temp_target = target + ".tmp"
|
|
||||||
download_file_with_progress(url, temp_target, progress_callback)
|
|
||||||
if os.path.exists(target):
|
|
||||||
try:
|
|
||||||
os.remove(target)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
shutil.move(temp_target, target)
|
|
||||||
return target
|
|
||||||
|
|
||||||
|
|
||||||
def install_ffmpeg(progress_callback=None):
|
|
||||||
"""yt-dlp tarafından resmi olarak önerilen taşınabilir FFmpeg yapısını indirip ayıklar."""
|
|
||||||
bin_dir = get_bin_dir()
|
|
||||||
os.makedirs(bin_dir, exist_ok=True)
|
|
||||||
zip_path = os.path.join(bin_dir, "ffmpeg_download.zip")
|
|
||||||
|
|
||||||
# yt-dlp resmi FFmpeg win64 yapısı (gpl)
|
|
||||||
url = "https://github.com/yt-dlp/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip"
|
|
||||||
|
|
||||||
download_file_with_progress(url, zip_path, progress_callback)
|
|
||||||
|
|
||||||
# Ayıkla ve ffmpeg.exe ile ffprobe.exe'yi bin_dir içine taşı
|
|
||||||
with zipfile.ZipFile(zip_path, 'r') as zf:
|
|
||||||
for member in zf.namelist():
|
|
||||||
filename = os.path.basename(member)
|
|
||||||
if filename in ("ffmpeg.exe", "ffprobe.exe"):
|
|
||||||
source = zf.open(member)
|
|
||||||
target_path = os.path.join(bin_dir, filename)
|
|
||||||
with open(target_path, "wb") as target_file:
|
|
||||||
shutil.copyfileobj(source, target_file)
|
|
||||||
|
|
||||||
try:
|
|
||||||
os.remove(zip_path)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return os.path.join(bin_dir, "ffmpeg.exe")
|
|
||||||
|
|
||||||
|
|
||||||
def _find_zen_profile() -> str | None:
|
|
||||||
"""Zen Browser için aktif Firefox tabanlı profil klasörünü bulur."""
|
|
||||||
appdata = os.getenv("APPDATA", "")
|
|
||||||
zen_root = os.path.join(appdata, "Zen")
|
|
||||||
profiles_ini = os.path.join(zen_root, "profiles.ini")
|
|
||||||
if os.path.isfile(profiles_ini):
|
|
||||||
try:
|
|
||||||
cp = configparser.ConfigParser()
|
|
||||||
cp.read(profiles_ini, encoding="utf-8")
|
|
||||||
for section in cp.sections():
|
|
||||||
if section.startswith("Install") and cp.has_option(section, "Default"):
|
|
||||||
rel = cp.get(section, "Default")
|
|
||||||
cand = os.path.normpath(os.path.join(zen_root, rel))
|
|
||||||
if os.path.isdir(cand):
|
|
||||||
return cand
|
|
||||||
for section in cp.sections():
|
|
||||||
if cp.has_option(section, "Path"):
|
|
||||||
p = cp.get(section, "Path")
|
|
||||||
is_rel = cp.get(section, "IsRelative", fallback="1") == "1"
|
|
||||||
cand = os.path.normpath(os.path.join(zen_root, p) if is_rel else p)
|
|
||||||
if os.path.isdir(cand) and (cp.get(section, "Default", fallback="0") == "1" or "default" in p.lower()):
|
|
||||||
return cand
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
zen_profiles = os.path.join(zen_root, "Profiles")
|
|
||||||
if os.path.isdir(zen_profiles):
|
|
||||||
folders = [os.path.join(zen_profiles, f) for f in os.listdir(zen_profiles) if os.path.isdir(os.path.join(zen_profiles, f))]
|
|
||||||
for folder in folders:
|
|
||||||
if "default-release" in os.path.basename(folder).lower() or "default" in os.path.basename(folder).lower():
|
|
||||||
if os.path.isfile(os.path.join(folder, "cookies.sqlite")):
|
|
||||||
return folder
|
|
||||||
for folder in folders:
|
|
||||||
if os.path.isfile(os.path.join(folder, "cookies.sqlite")):
|
|
||||||
return folder
|
|
||||||
if folders:
|
|
||||||
return folders[0]
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_cookies_args(mode: str, browser: str = "firefox", cookies_file: str = ""):
|
|
||||||
"""Çerez parametrelerini akıllıca çözer. Zen Browser için Firefox profilini bulur."""
|
|
||||||
if not mode or mode in ("none", "off", "kapali", "kapalı"):
|
|
||||||
return []
|
|
||||||
|
|
||||||
if mode == "file":
|
|
||||||
if cookies_file and cookies_file != "Seçilmedi" and os.path.isfile(cookies_file):
|
|
||||||
return ["--cookies", cookies_file]
|
|
||||||
raise FileNotFoundError(
|
|
||||||
"Seçilen cookies.txt dosyası bulunamadı. Ayarlar bölümünden geçerli bir dosya seçin veya çerez kullanımını kapatın."
|
|
||||||
)
|
|
||||||
|
|
||||||
if mode == "browser":
|
|
||||||
b = (browser or "").lower().strip()
|
|
||||||
if b == "zen":
|
|
||||||
profile_path = _find_zen_profile()
|
|
||||||
if profile_path:
|
|
||||||
return ["--cookies-from-browser", f"firefox:{profile_path}"]
|
|
||||||
return ["--cookies-from-browser", "firefox"]
|
|
||||||
|
|
||||||
return ["--cookies-from-browser", b]
|
|
||||||
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
def test_browser_cookies(browser_name: str):
|
|
||||||
"""Belirtilen tarayıcıdan çerez çekilip çekilemediğini test eder."""
|
|
||||||
args = resolve_cookies_args("browser", browser_name)
|
|
||||||
if not args:
|
|
||||||
return False, "Geçersiz çerez parametresi"
|
|
||||||
|
|
||||||
cmd = get_ytdlp_cmd() + args + ["--simulate", "--no-warnings", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"]
|
|
||||||
flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
|
||||||
try:
|
|
||||||
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, creationflags=flags, timeout=15)
|
|
||||||
if proc.returncode == 0:
|
|
||||||
return True, f"✅ {browser_name.capitalize()} çerezleri başarıyla okundu!"
|
|
||||||
|
|
||||||
err = proc.stderr.lower()
|
|
||||||
if "failed to decrypt with dpapi" in err or "dpapi" in err or "appbound" in err:
|
|
||||||
return False, (
|
|
||||||
f"⚠️ {browser_name.capitalize()}: Windows DPAPI / App-Bound güvenlik koruması nedeniyle doğrudan çerez okunamadı. "
|
|
||||||
f"Çözüm: Firefox/Zen kullanın veya çerezleri 'cookies.txt' eklentisiyle dışa aktarıp 'cookies.txt' modunda yükleyin."
|
|
||||||
)
|
|
||||||
if "could not copy" in err or "database" in err or "locked" in err:
|
|
||||||
return False, f"⚠️ {browser_name.capitalize()} şu an açık olduğu için Windows dosyayı kilitliyor. Tarayıcıyı kapatıp tekrar deneyin."
|
|
||||||
if "could not find" in err:
|
|
||||||
return False, f"⚠️ {browser_name.capitalize()} çerez veritabanı bulunamadı. Bu tarayıcının sisteminizde yüklü olduğundan emin olun."
|
|
||||||
return False, f"Hata: {proc.stderr.strip()[:180]}"
|
|
||||||
except Exception as ex:
|
|
||||||
return False, str(ex)
|
|
||||||
|
|
@ -1,90 +0,0 @@
|
||||||
import re
|
|
||||||
|
|
||||||
DIAGNOSTIC_RULES = [
|
|
||||||
{
|
|
||||||
"keywords": ["confirm your age", "sign in to confirm your age", "age-restricted"],
|
|
||||||
"title": "🔞 Yaş Kısıtlamalı Video",
|
|
||||||
"solution": "Bu video yaş sınırına sahiptir. Ayarlar veya Çerezler bölümünden tarayıcınızı seçerek veya 'cookies.txt' dosyası ekleyerek indirmeyi yeniden deneyin."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["private video", "this video is private"],
|
|
||||||
"title": "🔒 Gizli (Özel) Video",
|
|
||||||
"solution": "Bu video gizli veya yalnızca belirli kullanıcılara açıktır. İndirebilmek için videoya erişim izni olan bir hesabın çerezlerini (cookies) yüklemelisiniz."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["members-only", "join this channel"],
|
|
||||||
"title": "⭐ Katıl / Üyelere Özel Video",
|
|
||||||
"solution": "Bu video yalnızca kanal üyelerine özeldir. Yalnızca bu kanala ücretli üye olan hesabınızın çerezlerini (cookies.txt) aktararak indirebilirsiniz."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["n challenge solving failed", "javascript runtime", "wiki/ejs", "no supported javascript runtime"],
|
|
||||||
"title": "⚡ JavaScript EJS Motoru Gerekli",
|
|
||||||
"solution": "YouTube'un yeni güvenlik imzalarını çözmek için JavaScript motoru (Deno) gereklidir. Uygulamanız Deno motorunu bin/ klasörüne otomatik olarak entegre etmiştir."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["only images are available for download", "requested format is not available"],
|
|
||||||
"title": "⚠️ Video Akışı Bulunamadı",
|
|
||||||
"solution": "Video akışı çekilemedi (yalnızca kapak görselleri mevcut). Bu video kısıtlı/üyelere özel olabilir veya yaş doğrulaması gerektirebilir."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["not available in your country", "uploader has not made this video available in your country"],
|
|
||||||
"title": "🌍 Bölge Kısıtlaması (Geo-block)",
|
|
||||||
"solution": "Bu video ülkenizde kullanılamıyor. Ayarlar sekmesinden bir Proxy tanımlayabilir veya VPN kullanarak deneyebilirsiniz."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["http error 403", "403: forbidden", "sign in to confirm you’re not a bot", "bot detection"],
|
|
||||||
"title": "🛡️ YouTube Bot / 403 Koruması",
|
|
||||||
"solution": "YouTube sunucuları doğrudan erişimi kısıtladı. Tarayıcınızdan taze çerezler (cookies) aktararak kimlik doğrulamasını yenileyin."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["ffmpeg is not installed", "ffmpeg not found", "ffmpeg missing", "ffprobe not found"],
|
|
||||||
"title": "⚠️ FFmpeg Bulunamadı",
|
|
||||||
"solution": "Yüksek çözünürlüklü video birleştirme ve MP3 dönüşümleri için FFmpeg gereklidir. Ayarlar sekmesinden '⚡ 1-Tıkla FFmpeg Kur' butonuna tıklayarak otomatik kurabilirsiniz."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["permission denied", "permissionerror", "access is denied"],
|
|
||||||
"title": "⛔ Klasör Yazma İzni Reddedildi",
|
|
||||||
"solution": "Seçilen kayıt klasörüne yazma izniniz yok. Lütfen 'İndirilenler' veya masaüstünde farklı bir klasör seçin ya da uygulamayı yönetici olarak başlatın."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["no space left on device", "disk full"],
|
|
||||||
"title": "💾 Yetersiz Disk Alanı",
|
|
||||||
"solution": "Kayıt yapılan diskte yeterli boş alan bulunmuyor. Lütfen diskte yer açın veya başka bir sürücü seçin."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["is not a valid url", "unsupported url"],
|
|
||||||
"title": "🔗 Geçersiz veya Desteklenmeyen URL",
|
|
||||||
"solution": "Girilen bağlantı geçerli bir video/ses bağlantısı değil. Lütfen URL'yi tarayıcınızdan kopyalayıp tekrar yapıştırın."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["could not copy chrome cookie database", "could not copy", "cookie database"],
|
|
||||||
"title": "🍪 Tarayıcı Çerez Dosyası Kilitli",
|
|
||||||
"solution": "Seçilen tarayıcı açık olduğu için Windows çerez dosyasını kilitliyor. Çözüm: İndirme yaparken tarayıcıyı tamamen kapatın veya 'cookies.txt' dosya seçeneğini kullanın."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["failed to decrypt with dpapi", "dpapi"],
|
|
||||||
"title": "🔐 Windows DPAPI Koruması",
|
|
||||||
"solution": "Windows güvenlik koruması (DPAPI) nedeniyle tarayıcıdan doğrudan çerez çekilemedi. Çözüm: 1) Normal videolarda çerez gerekmez, Çerezleri 'Kapalı' yapabilirsiniz. 2) Yaş kısıtlamalı videolar için tarayıcınıza 'Get cookies.txt' eklentisi kurup dışa aktardığınız dosyayı yükleyin."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["unable to download video subtitles", "http error 429", "too many requests"],
|
|
||||||
"title": "⏳ Altyazı / İstek Kotası Aşıldı (HTTP 429)",
|
|
||||||
"solution": "Sunucu çok fazla altyazı veya veri isteğini geçici olarak kısıtladı. 'Altyazı göm' seçeneğini kapatarak videoyu hemen indirebilir veya Ayarlar'dan çerez (cookies.txt) ekleyerek kotayı aşabilirsiniz."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"keywords": ["the channel is not currently live", "usernotlive"],
|
|
||||||
"title": "📡 Yayıncı Şu Anda Çevrimdışı",
|
|
||||||
"solution": "Bu Kick/Twitch kanalı şu anda canlı yayında değil. Geçmiş yayınları (VOD) veya klipleri (Clips) sekmeden seçerek indirebilir ya da 'Yayın Açılmasını Bekle' seçeneğini aktif edebilirsiniz."
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
def diagnose(line: str) -> dict | None:
|
|
||||||
"""Verilen log satırını analiz edip varsa tanı ve Türkçe çözüm önerisi döndürür."""
|
|
||||||
lower_line = line.lower()
|
|
||||||
for rule in DIAGNOSTIC_RULES:
|
|
||||||
if any(kw in lower_line for kw in rule["keywords"]):
|
|
||||||
return {
|
|
||||||
"title": rule["title"],
|
|
||||||
"solution": rule["solution"]
|
|
||||||
}
|
|
||||||
return None
|
|
||||||
|
|
@ -1,633 +0,0 @@
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import re
|
|
||||||
import subprocess
|
|
||||||
import threading
|
|
||||||
from core.dependencies import find_executable, get_ffmpeg_dir, get_ytdlp_cmd
|
|
||||||
from core.diagnostics import diagnose
|
|
||||||
|
|
||||||
class DownloadEngine:
|
|
||||||
_PROGRESS_RE = re.compile(
|
|
||||||
r"\[PROGRESS\]\s*(?P<pct>[\d.]+)(?:%\s*)?\|\s*(?P<speed>.*?)\s*\|\s*(?P<total>.*?)\s*\|\s*(?P<eta>[^|]*)"
|
|
||||||
r"(?:\|\s*(?P<dl>.*?)\s*\|\s*(?P<est>.*))?"
|
|
||||||
)
|
|
||||||
_DL_RE = re.compile(
|
|
||||||
r"\[download\]\s+(?P<pct>[\d.]+)%\s+of\s+~?(?P<total>\S+)\s+"
|
|
||||||
r"at\s+(?P<speed>.*?)\s+ETA\s+(?P<eta>\S+)"
|
|
||||||
)
|
|
||||||
_FFMPEG_PROGRESS_RE = re.compile(
|
|
||||||
r"size=\s*(?P<size>\d+)\s*(?P<unit>[kKmMgG]?i?[bB])\s+"
|
|
||||||
r"time=\s*(?P<time>[\d:.]+)\s+"
|
|
||||||
r"bitrate=\s*(?P<bitrate>[\d.]+)\s*(?P<br_unit>[kKmMgG]?bits/s)"
|
|
||||||
)
|
|
||||||
_DEST_RE = re.compile(
|
|
||||||
r"\[(?:download|Merger|ExtractAudio|FixupM3u8|VideoRemuxer|VideoConvertor)\]\s+"
|
|
||||||
r"(?:Destination:\s+|Merging formats into\s+\"|Writing video subtitles to:\s+|Remuxing video from \S+ to\s+\"?)(?P<path>[^\"]+)"
|
|
||||||
)
|
|
||||||
_ALREADY_RE = re.compile(
|
|
||||||
r"\[download\]\s+(?P<path>.+?)\s+has already been downloaded"
|
|
||||||
)
|
|
||||||
_FINAL_PATH_PREFIX = "[FINAL_PATH] "
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self._proc = None
|
|
||||||
self._running = False
|
|
||||||
self._cancelled = False
|
|
||||||
self._current_file = None
|
|
||||||
self._is_live_session = False
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def is_running(self):
|
|
||||||
return self._running
|
|
||||||
|
|
||||||
def cancel(self):
|
|
||||||
"""Devam eden indirmeyi ve tüm alt süreç ağacını güvenle ve arayüzü dondurmadan sonlandırır."""
|
|
||||||
with self._lock:
|
|
||||||
if not self._running or not self._proc:
|
|
||||||
return
|
|
||||||
self._cancelled = True
|
|
||||||
proc = self._proc
|
|
||||||
|
|
||||||
def _do_kill():
|
|
||||||
try:
|
|
||||||
if sys.platform == "win32":
|
|
||||||
# Canlı yayın kaydında FFmpeg'in MP4 moov atomunu yazıp dosyayı sağlam kapatması için
|
|
||||||
# önce nazik sonlandırma (/F olmadan) dene, 2.5sn içinde kapanmazsa /F ile zorla kapat.
|
|
||||||
subprocess.run(
|
|
||||||
["taskkill", "/T", "/PID", str(proc.pid)],
|
|
||||||
creationflags=subprocess.CREATE_NO_WINDOW,
|
|
||||||
stdout=subprocess.DEVNULL,
|
|
||||||
stderr=subprocess.DEVNULL
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
proc.wait(timeout=2.5)
|
|
||||||
return
|
|
||||||
except subprocess.TimeoutExpired:
|
|
||||||
pass
|
|
||||||
subprocess.run(
|
|
||||||
["taskkill", "/F", "/T", "/PID", str(proc.pid)],
|
|
||||||
creationflags=subprocess.CREATE_NO_WINDOW,
|
|
||||||
stdout=subprocess.DEVNULL,
|
|
||||||
stderr=subprocess.DEVNULL
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
proc.terminate()
|
|
||||||
try:
|
|
||||||
proc.wait(timeout=2.5)
|
|
||||||
except subprocess.TimeoutExpired:
|
|
||||||
proc.kill()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
threading.Thread(target=_do_kill, daemon=True).start()
|
|
||||||
|
|
||||||
def start_download(self, cmd_args, callbacks):
|
|
||||||
"""
|
|
||||||
İndirmeyi arka planda başlatır.
|
|
||||||
callbacks dict:
|
|
||||||
- on_progress(pct, speed, total, eta)
|
|
||||||
- on_log(line, tag)
|
|
||||||
- on_status(msg)
|
|
||||||
- on_complete(success, output_path, error_msg)
|
|
||||||
"""
|
|
||||||
with self._lock:
|
|
||||||
if self._running:
|
|
||||||
return False
|
|
||||||
self._running = True
|
|
||||||
self._cancelled = False
|
|
||||||
self._current_file = None
|
|
||||||
self._is_live_session = ("--hls-use-mpegts" in cmd_args)
|
|
||||||
|
|
||||||
thread = threading.Thread(target=self._worker, args=(cmd_args, callbacks), daemon=True)
|
|
||||||
thread.start()
|
|
||||||
return True
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _iter_unbuffered_lines(pipe):
|
|
||||||
"""
|
|
||||||
Subprocess stdout borusundan 8KB tampon (buffer) beklemeden anlık okuma yapar.
|
|
||||||
Hem '\\n' (yt-dlp) hem de '\\r' (ffmpeg canlı yayın / kesit ilerlemesi) karakterlerinde
|
|
||||||
satırı anında (0ms gecikmeyle) döndürür.
|
|
||||||
"""
|
|
||||||
fd = None
|
|
||||||
try:
|
|
||||||
fd = pipe.fileno()
|
|
||||||
except Exception:
|
|
||||||
fd = None
|
|
||||||
|
|
||||||
buf = ""
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
if fd is not None:
|
|
||||||
chunk = os.read(fd, 1024)
|
|
||||||
else:
|
|
||||||
chunk = pipe.read(256)
|
|
||||||
except OSError:
|
|
||||||
break
|
|
||||||
if not chunk:
|
|
||||||
break
|
|
||||||
if isinstance(chunk, bytes):
|
|
||||||
text = chunk.decode("utf-8", errors="replace")
|
|
||||||
else:
|
|
||||||
text = chunk
|
|
||||||
buf += text
|
|
||||||
while True:
|
|
||||||
idx_r = buf.find("\r")
|
|
||||||
idx_n = buf.find("\n")
|
|
||||||
if idx_r == -1 and idx_n == -1:
|
|
||||||
break
|
|
||||||
if idx_r != -1 and (idx_n == -1 or idx_r < idx_n):
|
|
||||||
split_at = idx_r
|
|
||||||
# Eğer \r\n yan yanaysa ikisini birden atla
|
|
||||||
next_start = split_at + 2 if (split_at + 1 < len(buf) and buf[split_at + 1] == "\n") else split_at + 1
|
|
||||||
else:
|
|
||||||
split_at = idx_n
|
|
||||||
next_start = split_at + 1
|
|
||||||
|
|
||||||
line = buf[:split_at].strip()
|
|
||||||
buf = buf[next_start:]
|
|
||||||
if line:
|
|
||||||
yield line
|
|
||||||
|
|
||||||
if buf.strip():
|
|
||||||
yield buf.strip()
|
|
||||||
|
|
||||||
def _remux_live_file_if_needed(self, file_path, cb):
|
|
||||||
"""
|
|
||||||
Canlı yayın (--hls-use-mpegts) kaydı durdurulduğunda MPEG-TS akışını
|
|
||||||
standart MP4 kapsayıcısına (moov atom + süre bilgisi ile) kayıpsız dönüştürür.
|
|
||||||
"""
|
|
||||||
if not file_path or not os.path.isfile(file_path):
|
|
||||||
return file_path
|
|
||||||
try:
|
|
||||||
if os.path.getsize(file_path) < 32 * 1024:
|
|
||||||
return file_path
|
|
||||||
if not file_path.lower().endswith(".mp4"):
|
|
||||||
return file_path
|
|
||||||
ffmpeg_exe = find_executable("ffmpeg")
|
|
||||||
if not ffmpeg_exe:
|
|
||||||
return file_path
|
|
||||||
|
|
||||||
if cb.get("on_status"):
|
|
||||||
cb["on_status"]("Canlı yayın MP4 olarak kaydediliyor...")
|
|
||||||
temp_ts = file_path + ".remux_tmp.ts"
|
|
||||||
os.replace(file_path, temp_ts)
|
|
||||||
flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
|
||||||
res = subprocess.run(
|
|
||||||
[ffmpeg_exe, "-y", "-hide_banner", "-loglevel", "error", "-i", temp_ts, "-c", "copy", "-bsf:a", "aac_adtstoasc", "-movflags", "+faststart", file_path],
|
|
||||||
creationflags=flags,
|
|
||||||
stdout=subprocess.DEVNULL,
|
|
||||||
stderr=subprocess.DEVNULL,
|
|
||||||
timeout=30
|
|
||||||
)
|
|
||||||
if res.returncode == 0 and os.path.isfile(file_path) and os.path.getsize(file_path) > 0:
|
|
||||||
try:
|
|
||||||
os.remove(temp_ts)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
# Geri al
|
|
||||||
if os.path.isfile(temp_ts):
|
|
||||||
os.replace(temp_ts, file_path)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return file_path
|
|
||||||
|
|
||||||
def _worker(self, cmd_args, cb):
|
|
||||||
rc = -1
|
|
||||||
error_message = None
|
|
||||||
last_destination = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
env = os.environ.copy()
|
|
||||||
env["PYTHONIOENCODING"] = "utf-8"
|
|
||||||
env["PYTHONUNBUFFERED"] = "1"
|
|
||||||
from core.config import get_bin_dir
|
|
||||||
b_dir = get_bin_dir()
|
|
||||||
if b_dir and b_dir not in env.get("PATH", ""):
|
|
||||||
env["PATH"] = f"{b_dir};{env.get('PATH', '')}"
|
|
||||||
|
|
||||||
flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
|
||||||
self._proc = subprocess.Popen(
|
|
||||||
cmd_args,
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.STDOUT,
|
|
||||||
bufsize=0,
|
|
||||||
creationflags=flags,
|
|
||||||
env=env
|
|
||||||
)
|
|
||||||
|
|
||||||
if self._proc and self._proc.stdout:
|
|
||||||
for line in self._iter_unbuffered_lines(self._proc.stdout):
|
|
||||||
if line.startswith(self._FINAL_PATH_PREFIX):
|
|
||||||
final_p = line[len(self._FINAL_PATH_PREFIX):].strip().strip('"')
|
|
||||||
if final_p and final_p != "NA":
|
|
||||||
last_destination = final_p
|
|
||||||
self._current_file = final_p
|
|
||||||
continue
|
|
||||||
|
|
||||||
if line.startswith("[kick:live]") or "live_status" in line:
|
|
||||||
self._is_live_session = True
|
|
||||||
|
|
||||||
# 1. Dosya yolu yakalama
|
|
||||||
m_dest = self._DEST_RE.search(line) or self._ALREADY_RE.search(line)
|
|
||||||
if m_dest:
|
|
||||||
dest = m_dest.group("path").strip().strip('"')
|
|
||||||
if not dest.endswith((".part", ".ytdl", ".vtt", ".srt", ".ass", ".lrc")):
|
|
||||||
last_destination = dest
|
|
||||||
self._current_file = dest
|
|
||||||
|
|
||||||
# Durum / Aşama güncellemesi
|
|
||||||
if line.startswith("[ExtractAudio]"):
|
|
||||||
if cb.get("on_status"):
|
|
||||||
cb["on_status"]("Ses dönüştürülüyor...")
|
|
||||||
elif line.startswith("[Merger]"):
|
|
||||||
if cb.get("on_status"):
|
|
||||||
cb["on_status"]("Formatlar birleştiriliyor...")
|
|
||||||
elif line.startswith(("[EmbedThumbnail]", "[ThumbnailsConvertor]")):
|
|
||||||
if cb.get("on_status"):
|
|
||||||
cb["on_status"]("Kapak resmi ekleniyor...")
|
|
||||||
elif line.startswith("[Metadata]"):
|
|
||||||
if cb.get("on_status"):
|
|
||||||
cb["on_status"]("Üstveri ekleniyor...")
|
|
||||||
elif line.startswith("[SponsorBlock]"):
|
|
||||||
if cb.get("on_status"):
|
|
||||||
cb["on_status"]("Sponsorlu bölümler kesiliyor...")
|
|
||||||
elif line.startswith("[download] Destination:"):
|
|
||||||
if cb.get("on_status"):
|
|
||||||
cb["on_status"]("Canlı Yayın Kaydediliyor..." if self._is_live_session else "İndiriliyor...")
|
|
||||||
|
|
||||||
# 2. İlerleme ayrıştırma (yt-dlp + FFmpeg canlı yayın/kesit ilerlemesi)
|
|
||||||
parsed = self._parse_progress(line, cb.get("on_progress"), cb.get("on_status"))
|
|
||||||
|
|
||||||
# 3. Akıllı Hata Teşhisi
|
|
||||||
diag = diagnose(line)
|
|
||||||
if diag:
|
|
||||||
if cb.get("on_log"):
|
|
||||||
cb["on_log"](f"💡 {diag['title']}: {diag['solution']}", "accent")
|
|
||||||
|
|
||||||
# 4. Log etiketi belirleme
|
|
||||||
tag = "info"
|
|
||||||
if "ERROR:" in line:
|
|
||||||
tag = "error"
|
|
||||||
error_message = line
|
|
||||||
elif "WARNING:" in line:
|
|
||||||
tag = "warn"
|
|
||||||
elif "[download] 100%" in line or "100% of" in line:
|
|
||||||
tag = "success"
|
|
||||||
|
|
||||||
is_progress_line = (
|
|
||||||
line.startswith("[PROGRESS]")
|
|
||||||
or (parsed and bool(self._DL_RE.search(line) or self._FFMPEG_PROGRESS_RE.search(line)))
|
|
||||||
)
|
|
||||||
if cb.get("on_log") and not is_progress_line:
|
|
||||||
cb["on_log"](line, tag)
|
|
||||||
|
|
||||||
if self._proc:
|
|
||||||
self._proc.wait()
|
|
||||||
rc = self._proc.returncode
|
|
||||||
|
|
||||||
except FileNotFoundError as fnf:
|
|
||||||
error_message = (
|
|
||||||
"yt-dlp veya FFmpeg sistemde bulunamadı. "
|
|
||||||
"Lütfen Ayarlar sekmesine giderek '⚡ Kur' butonu ile bileşenleri kurun."
|
|
||||||
)
|
|
||||||
if cb.get("on_log"):
|
|
||||||
cb["on_log"](f"❌ {error_message}", "error")
|
|
||||||
except Exception as ex:
|
|
||||||
error_message = str(ex)
|
|
||||||
if cb.get("on_log"):
|
|
||||||
cb["on_log"](f"❌ Kritik Hata: {ex}", "error")
|
|
||||||
|
|
||||||
finally:
|
|
||||||
with self._lock:
|
|
||||||
self._running = False
|
|
||||||
cancelled = self._cancelled
|
|
||||||
is_live_session = self._is_live_session
|
|
||||||
if self._proc and self._proc.stdout:
|
|
||||||
try:
|
|
||||||
self._proc.stdout.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._proc = None
|
|
||||||
|
|
||||||
target_file = last_destination or self._current_file
|
|
||||||
# Eğer canlı yayın kaydı kullanıcı tarafından durdurulduysa ve diske veri kaydedildiyse,
|
|
||||||
# bunu iptal değil başarılı canlı yayın kaydı olarak tamamla ve MP4 kapsayıcısını onar!
|
|
||||||
if is_live_session and target_file and os.path.isfile(target_file):
|
|
||||||
try:
|
|
||||||
if os.path.getsize(target_file) > 32 * 1024:
|
|
||||||
target_file = self._remux_live_file_if_needed(target_file, cb)
|
|
||||||
cancelled = False
|
|
||||||
rc = 0
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
success = (rc == 0 and not cancelled)
|
|
||||||
if cb.get("on_complete"):
|
|
||||||
cb["on_complete"](success, target_file, error_message, cancelled)
|
|
||||||
|
|
||||||
def _parse_progress(self, line, on_progress, on_status=None):
|
|
||||||
if not on_progress:
|
|
||||||
return False
|
|
||||||
|
|
||||||
# 1. Özel [PROGRESS] template kontrolü (Normal + HLS/m3u8 yayınlar)
|
|
||||||
m = self._PROGRESS_RE.search(line)
|
|
||||||
if m:
|
|
||||||
try:
|
|
||||||
pct = float(m.group("pct").strip())
|
|
||||||
speed = m.group("speed").strip()
|
|
||||||
total = m.group("total").strip()
|
|
||||||
eta = m.group("eta").strip()
|
|
||||||
dl = (m.group("dl") or "").strip()
|
|
||||||
est = (m.group("est") or "").strip()
|
|
||||||
|
|
||||||
def _is_na(val):
|
|
||||||
return not val or any(x in val.lower() for x in ["unknown", "na", "n/a", "—", "~0.00"])
|
|
||||||
|
|
||||||
speed = "—" if _is_na(speed) else speed
|
|
||||||
if _is_na(total):
|
|
||||||
if not _is_na(dl) and not _is_na(est):
|
|
||||||
total = f"{dl} / ~{est}"
|
|
||||||
elif not _is_na(dl):
|
|
||||||
total = dl
|
|
||||||
elif not _is_na(est):
|
|
||||||
total = f"~{est}"
|
|
||||||
else:
|
|
||||||
total = "—"
|
|
||||||
eta = "—" if _is_na(eta) else eta
|
|
||||||
|
|
||||||
on_progress(pct, speed, total, eta)
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# 2. FFmpeg canlı yayın ve kesit (--download-sections) ilerleme satırı
|
|
||||||
m_ff = self._FFMPEG_PROGRESS_RE.search(line)
|
|
||||||
if m_ff:
|
|
||||||
try:
|
|
||||||
raw_size = int(m_ff.group("size"))
|
|
||||||
unit = m_ff.group("unit").lower()
|
|
||||||
if unit.startswith("k"):
|
|
||||||
bytes_val = raw_size * 1024
|
|
||||||
elif unit.startswith("m"):
|
|
||||||
bytes_val = raw_size * 1024 * 1024
|
|
||||||
elif unit.startswith("g"):
|
|
||||||
bytes_val = raw_size * 1024 * 1024 * 1024
|
|
||||||
else:
|
|
||||||
bytes_val = raw_size
|
|
||||||
|
|
||||||
if bytes_val >= 1024 * 1024 * 1024:
|
|
||||||
size_str = f"{bytes_val / (1024 * 1024 * 1024):.2f} GB"
|
|
||||||
else:
|
|
||||||
size_str = f"{bytes_val / (1024 * 1024):.1f} MB"
|
|
||||||
|
|
||||||
br_val = float(m_ff.group("bitrate"))
|
|
||||||
mb_s = (br_val / 8.0) / 1024.0
|
|
||||||
speed_str = f"{mb_s:.2f} MB/s" if mb_s >= 0.05 else f"{br_val:.0f} kbps"
|
|
||||||
time_str = m_ff.group("time").split(".")[0]
|
|
||||||
|
|
||||||
# pct = -1.0 -> Canlı kayıt / FFmpeg akış modu
|
|
||||||
on_progress(-1.0, speed_str, size_str, f"Kayıt: {time_str}")
|
|
||||||
if on_status and self._is_live_session:
|
|
||||||
on_status(f"🔴 Canlı Yayın Kaydediliyor ({size_str} · {time_str})")
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# 3. Standart yt-dlp ilerleme satırı
|
|
||||||
m = self._DL_RE.search(line)
|
|
||||||
if m:
|
|
||||||
try:
|
|
||||||
pct = float(m.group("pct"))
|
|
||||||
total = m.group("total")
|
|
||||||
speed = m.group("speed").strip()
|
|
||||||
eta = m.group("eta").strip()
|
|
||||||
on_progress(pct, speed, total, eta)
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def build_command(url, output_dir, options):
|
|
||||||
"""
|
|
||||||
yt-dlp için tüm seçenekleri birleştirip komut listesini üretir.
|
|
||||||
options alanları:
|
|
||||||
- mode: "single" veya "playlist"
|
|
||||||
- media_type: "video" veya "audio"
|
|
||||||
- format: "mp4", "mkv", "webm", "mp3", "m4a", "flac", "wav" vb.
|
|
||||||
- quality: "Best Quality (En İyi)" veya "1080p", "720p" / "320 kbps"
|
|
||||||
- cookies_args: list
|
|
||||||
- embed_subtitles: bool
|
|
||||||
- subtitle_lang: str
|
|
||||||
- embed_thumbnail: bool
|
|
||||||
- add_metadata: bool
|
|
||||||
- concurrent_fragments: int
|
|
||||||
- playlist_start: str
|
|
||||||
- playlist_end: str
|
|
||||||
- ignore_errors: bool
|
|
||||||
- speed_limit: str
|
|
||||||
- proxy: str
|
|
||||||
"""
|
|
||||||
ytdlp_cmd = get_ytdlp_cmd()
|
|
||||||
cmd = list(ytdlp_cmd) + ["--newline"]
|
|
||||||
|
|
||||||
# Yerel FFmpeg kontrolü
|
|
||||||
ffmpeg_dir = get_ffmpeg_dir()
|
|
||||||
if ffmpeg_dir:
|
|
||||||
cmd += ["--ffmpeg-location", ffmpeg_dir]
|
|
||||||
|
|
||||||
# Çerezler
|
|
||||||
cookies_args = options.get("cookies_args") or []
|
|
||||||
cmd.extend(cookies_args)
|
|
||||||
|
|
||||||
media_type = options.get("media_type", "video")
|
|
||||||
out_format = options.get("format", "mp4" if media_type == "video" else "mp3").lower()
|
|
||||||
quality = options.get("quality", "Best Quality (En İyi)")
|
|
||||||
|
|
||||||
# Video / Ses Formatı Seçimi
|
|
||||||
if media_type == "video":
|
|
||||||
if "Best" in quality:
|
|
||||||
if out_format == "mp4":
|
|
||||||
cmd += ["-f", "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]/bv+ba/b", "--merge-output-format", "mp4"]
|
|
||||||
elif out_format == "mkv":
|
|
||||||
cmd += ["-f", "bv*+ba/b", "--merge-output-format", "mkv"]
|
|
||||||
elif out_format == "webm":
|
|
||||||
cmd += ["-f", "bv*[ext=webm]+ba[ext=webm]/b[ext=webm]/bv+ba/b", "--merge-output-format", "webm"]
|
|
||||||
else:
|
|
||||||
cmd += ["-f", "bv*+ba/b", "--merge-output-format", out_format]
|
|
||||||
else:
|
|
||||||
height = re.search(r"\d+", quality)
|
|
||||||
num_h = height.group(0) if height else "1080"
|
|
||||||
if out_format == "mp4":
|
|
||||||
cmd += [
|
|
||||||
"-f", f"bestvideo[height<={num_h}][ext=mp4]+bestaudio[ext=m4a]/bestvideo[height<={num_h}]+bestaudio/best[height<={num_h}]",
|
|
||||||
"--merge-output-format", "mp4"
|
|
||||||
]
|
|
||||||
else:
|
|
||||||
cmd += [
|
|
||||||
"-f", f"bestvideo[height<={num_h}]+bestaudio/best[height<={num_h}]",
|
|
||||||
"--merge-output-format", out_format
|
|
||||||
]
|
|
||||||
else:
|
|
||||||
# Audio indirme
|
|
||||||
cmd += ["-x", "--audio-format", out_format]
|
|
||||||
if "Best" in quality:
|
|
||||||
cmd += ["--audio-quality", "0"]
|
|
||||||
else:
|
|
||||||
bitrate = re.search(r"\d+", quality)
|
|
||||||
num_b = bitrate.group(0) if bitrate else "320"
|
|
||||||
cmd += ["--audio-quality", f"{num_b}k"]
|
|
||||||
|
|
||||||
# Gelişmiş Seçenekler (Kapak resmi yalnızca desteklenen formatlarda gömülür)
|
|
||||||
if options.get("embed_thumbnail", True) and out_format not in ("wav", "webm"):
|
|
||||||
cmd.append("--embed-thumbnail")
|
|
||||||
|
|
||||||
if options.get("add_metadata", True):
|
|
||||||
cmd.append("--add-metadata")
|
|
||||||
|
|
||||||
if options.get("embed_subtitles"):
|
|
||||||
langs = options.get("subtitle_lang", "tr,en")
|
|
||||||
cmd += ["--write-subs", "--write-auto-subs", "--sub-langs", langs, "--embed-subs"]
|
|
||||||
|
|
||||||
try:
|
|
||||||
concurrency = int(options.get("concurrent_fragments", 4))
|
|
||||||
except (TypeError, ValueError) as ex:
|
|
||||||
raise ValueError("Parça sayısı 1 ile 16 arasında bir tam sayı olmalıdır.") from ex
|
|
||||||
if not 1 <= concurrency <= 16:
|
|
||||||
raise ValueError("Parça sayısı 1 ile 16 arasında olmalıdır.")
|
|
||||||
if concurrency > 1:
|
|
||||||
cmd += ["--concurrent-fragments", str(concurrency)]
|
|
||||||
|
|
||||||
if options.get("mode") == "playlist" and options.get("ignore_errors", True):
|
|
||||||
cmd.append("--ignore-errors")
|
|
||||||
|
|
||||||
speed_limit = options.get("speed_limit")
|
|
||||||
if speed_limit:
|
|
||||||
cmd += ["--limit-rate", speed_limit]
|
|
||||||
|
|
||||||
proxy = options.get("proxy")
|
|
||||||
if proxy:
|
|
||||||
cmd += ["--proxy", proxy]
|
|
||||||
|
|
||||||
# İndirme Arşivi (--download-archive)
|
|
||||||
if options.get("use_download_archive"):
|
|
||||||
archive_path = options.get("archive_file")
|
|
||||||
if not archive_path:
|
|
||||||
from core.config import get_data_dir
|
|
||||||
archive_path = os.path.join(get_data_dir(), "archive.txt")
|
|
||||||
cmd += ["--download-archive", archive_path]
|
|
||||||
|
|
||||||
# SponsorBlock Entegrasyonu (--sponsorblock-remove)
|
|
||||||
if options.get("sponsorblock_remove"):
|
|
||||||
sb_cats = (options.get("sponsorblock_cats") or "sponsor,intro,outro").strip()
|
|
||||||
if sb_cats:
|
|
||||||
cmd += ["--sponsorblock-remove", sb_cats]
|
|
||||||
|
|
||||||
# Bölüm Kesme / Zaman Aralığı İndirme (--download-sections)
|
|
||||||
clip_section = clip_section_range(
|
|
||||||
options.get("clip_start"),
|
|
||||||
options.get("clip_end")
|
|
||||||
)
|
|
||||||
if clip_section:
|
|
||||||
cmd += ["--download-sections", clip_section]
|
|
||||||
|
|
||||||
# Canlı Yayın & HLS (Kick / Twitch / YouTube Live) seçenekleri
|
|
||||||
if options.get("is_live"):
|
|
||||||
cmd += ["--hls-use-mpegts", "--no-part"]
|
|
||||||
if options.get("wait_for_video"):
|
|
||||||
cmd += ["--wait-for-video", "15"]
|
|
||||||
if options.get("live_from_start"):
|
|
||||||
cmd.append("--live-from-start")
|
|
||||||
|
|
||||||
safe_output_dir = os.path.abspath(output_dir or os.getcwd())
|
|
||||||
|
|
||||||
# Playlist aralığı
|
|
||||||
if options.get("mode") == "playlist":
|
|
||||||
playlist_range = playlist_items_range(
|
|
||||||
options.get("playlist_start"),
|
|
||||||
options.get("playlist_end")
|
|
||||||
)
|
|
||||||
if playlist_range:
|
|
||||||
cmd += ["--playlist-items", playlist_range]
|
|
||||||
cmd.append("--yes-playlist")
|
|
||||||
cmd += ["-o", os.path.join(safe_output_dir, "%(playlist_title)s", "%(playlist_index)s - %(title)s.%(ext)s")]
|
|
||||||
else:
|
|
||||||
cmd.append("--no-playlist")
|
|
||||||
cmd += ["-o", os.path.join(safe_output_dir, "%(title)s.%(ext)s")]
|
|
||||||
|
|
||||||
# Kararlı ilerleme şablonu ve nihai dosya yolu çıktısı
|
|
||||||
# NOT: yt-dlp'de --print bayrağı varsayılan olarak --quiet ve --no-progress modunu tetikler.
|
|
||||||
# Bu yüzden --progress ve --no-quiet açıkça eklenmelidir ki konsol ve ilerleme çubuğu çalışsın.
|
|
||||||
# --progress-delta 0.15 ile ilerleme güncellemeleri optimize edilir, UI donması ve CPU aşırı yükü engellenir.
|
|
||||||
cmd += [
|
|
||||||
"--print",
|
|
||||||
"after_move:[FINAL_PATH] %(filepath)s",
|
|
||||||
"--progress",
|
|
||||||
"--no-quiet",
|
|
||||||
"--progress-delta",
|
|
||||||
"0.15",
|
|
||||||
"--progress-template",
|
|
||||||
"download:[PROGRESS] %(progress._percent_str)s | %(progress._speed_str)s | %(progress._total_bytes_str)s | %(progress._eta_str)s | %(progress._downloaded_bytes_str)s | %(progress._total_bytes_estimate_str)s"
|
|
||||||
]
|
|
||||||
|
|
||||||
cmd.append(url)
|
|
||||||
return cmd
|
|
||||||
|
|
||||||
engine = DownloadEngine()
|
|
||||||
|
|
||||||
|
|
||||||
_TIME_RE = re.compile(r"^(?:\d+:)?[0-5]?\d:[0-5]\d(?:\.\d+)?$|^\d+(?:\.\d+)?$")
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_timestamp_seconds(ts: str) -> float:
|
|
||||||
parts = ts.split(":")
|
|
||||||
if len(parts) == 1:
|
|
||||||
return float(parts[0])
|
|
||||||
if len(parts) == 2:
|
|
||||||
return int(parts[0]) * 60 + float(parts[1])
|
|
||||||
if len(parts) == 3:
|
|
||||||
return int(parts[0]) * 3600 + int(parts[1]) * 60 + float(parts[2])
|
|
||||||
raise ValueError("Geçersiz zaman formatı.")
|
|
||||||
|
|
||||||
|
|
||||||
def clip_section_range(start, end):
|
|
||||||
"""Zaman aralığını doğrular ve yt-dlp --download-sections değerini (*start-end) döndürür."""
|
|
||||||
start = str(start or "").strip()
|
|
||||||
end = str(end or "").strip()
|
|
||||||
if not start and not end:
|
|
||||||
return None
|
|
||||||
if start and not _TIME_RE.match(start):
|
|
||||||
raise ValueError("Başlangıç zamanı geçersiz (Örn: 01:20 veya 00:01:20 girin).")
|
|
||||||
if end and end.lower() != "inf" and not _TIME_RE.match(end):
|
|
||||||
raise ValueError("Bitiş zamanı geçersiz (Örn: 03:45 veya 00:03:45 girin).")
|
|
||||||
|
|
||||||
s_sec = _parse_timestamp_seconds(start) if start else 0.0
|
|
||||||
if end and end.lower() != "inf":
|
|
||||||
e_sec = _parse_timestamp_seconds(end)
|
|
||||||
if e_sec <= s_sec:
|
|
||||||
raise ValueError("Klip bitiş zamanı başlangıç zamanından büyük olmalıdır.")
|
|
||||||
|
|
||||||
return f"*{start or '00:00'}-{end or 'inf'}"
|
|
||||||
|
|
||||||
|
|
||||||
def playlist_items_range(start, end):
|
|
||||||
"""Validate playlist indexes and return yt-dlp's playlist-items value."""
|
|
||||||
start = str(start or "").strip()
|
|
||||||
end = str(end or "").strip()
|
|
||||||
if start and not start.isdigit():
|
|
||||||
raise ValueError("Başlangıç sırası pozitif bir tam sayı olmalıdır.")
|
|
||||||
if end and not end.isdigit():
|
|
||||||
raise ValueError("Bitiş sırası pozitif bir tam sayı olmalıdır.")
|
|
||||||
if start and int(start) < 1:
|
|
||||||
raise ValueError("Başlangıç sırası en az 1 olmalıdır.")
|
|
||||||
if end and int(end) < 1:
|
|
||||||
raise ValueError("Bitiş sırası en az 1 olmalıdır.")
|
|
||||||
if start and end and int(end) < int(start):
|
|
||||||
raise ValueError("Bitiş sırası başlangıç sırasından küçük olamaz.")
|
|
||||||
if start or end:
|
|
||||||
return f"{start or '1'}:{end}"
|
|
||||||
return None
|
|
||||||
135
core/history.py
|
|
@ -1,135 +0,0 @@
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import subprocess
|
|
||||||
from datetime import datetime
|
|
||||||
from uuid import uuid4
|
|
||||||
from core.config import get_data_dir
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class HistoryManager:
|
|
||||||
def __init__(self):
|
|
||||||
self.history_file = os.path.join(get_data_dir(), "history.json")
|
|
||||||
self.items = []
|
|
||||||
self.load()
|
|
||||||
|
|
||||||
def load(self):
|
|
||||||
if os.path.exists(self.history_file):
|
|
||||||
try:
|
|
||||||
with open(self.history_file, "r", encoding="utf-8") as f:
|
|
||||||
items = json.load(f)
|
|
||||||
if not isinstance(items, list):
|
|
||||||
raise ValueError("History file must contain a JSON list.")
|
|
||||||
self.items = items
|
|
||||||
except (OSError, json.JSONDecodeError, ValueError):
|
|
||||||
logger.exception("Could not load download history from %s", self.history_file)
|
|
||||||
self.items = []
|
|
||||||
else:
|
|
||||||
self.items = []
|
|
||||||
|
|
||||||
def save(self):
|
|
||||||
temp_path = self.history_file + ".tmp"
|
|
||||||
try:
|
|
||||||
with open(temp_path, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(self.items, f, indent=2, ensure_ascii=False)
|
|
||||||
f.flush()
|
|
||||||
os.replace(temp_path, self.history_file)
|
|
||||||
except (OSError, TypeError):
|
|
||||||
logger.exception("Could not save download history to %s", self.history_file)
|
|
||||||
try:
|
|
||||||
os.remove(temp_path)
|
|
||||||
except OSError:
|
|
||||||
logger.debug("Could not remove temporary history file %s", temp_path, exc_info=True)
|
|
||||||
|
|
||||||
def add(self, title, url, file_path, fmt_info, status="completed"):
|
|
||||||
size_str = "—"
|
|
||||||
if file_path and os.path.exists(file_path):
|
|
||||||
try:
|
|
||||||
if os.path.isdir(file_path):
|
|
||||||
bytes_size = 0
|
|
||||||
for root, _, files in os.walk(file_path):
|
|
||||||
for f in files:
|
|
||||||
fp = os.path.join(root, f)
|
|
||||||
try:
|
|
||||||
bytes_size += os.path.getsize(fp)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
bytes_size = os.path.getsize(file_path)
|
|
||||||
|
|
||||||
if bytes_size >= 1024 * 1024 * 1024:
|
|
||||||
size_str = f"{bytes_size / (1024*1024*1024):.2f} GB"
|
|
||||||
elif bytes_size >= 1024 * 1024:
|
|
||||||
size_str = f"{bytes_size / (1024*1024):.2f} MB"
|
|
||||||
else:
|
|
||||||
size_str = f"{bytes_size / 1024:.1f} KB"
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
item = {
|
|
||||||
"id": uuid4().hex,
|
|
||||||
"title": title or os.path.basename(file_path or url),
|
|
||||||
"url": url,
|
|
||||||
"path": file_path,
|
|
||||||
"format": fmt_info,
|
|
||||||
"size": size_str,
|
|
||||||
"date": datetime.now().strftime("%Y-%m-%d %H:%M"),
|
|
||||||
"status": status
|
|
||||||
}
|
|
||||||
# En yeni en üstte
|
|
||||||
self.items.insert(0, item)
|
|
||||||
# Maksimum 200 geçmiş kaydı sakla
|
|
||||||
if len(self.items) > 200:
|
|
||||||
self.items = self.items[:200]
|
|
||||||
self.save()
|
|
||||||
return item
|
|
||||||
|
|
||||||
def get_all(self):
|
|
||||||
return self.items
|
|
||||||
|
|
||||||
def remove(self, item_id):
|
|
||||||
self.items = [i for i in self.items if i.get("id") != item_id]
|
|
||||||
self.save()
|
|
||||||
|
|
||||||
def clear(self):
|
|
||||||
self.items = []
|
|
||||||
self.save()
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def show_in_folder(file_path):
|
|
||||||
"""Dosyayı Windows Explorer'da seçili olarak gösterir."""
|
|
||||||
if not file_path:
|
|
||||||
return False
|
|
||||||
|
|
||||||
path = os.path.normpath(file_path)
|
|
||||||
if os.path.exists(path):
|
|
||||||
if sys.platform == "win32":
|
|
||||||
subprocess.Popen(f'explorer /select,"{path}"')
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
subprocess.Popen(["xdg-open", os.path.dirname(path)])
|
|
||||||
return True
|
|
||||||
elif os.path.isdir(os.path.dirname(path)):
|
|
||||||
if sys.platform == "win32":
|
|
||||||
subprocess.Popen(f'explorer "{os.path.dirname(path)}"')
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def play_file(file_path):
|
|
||||||
"""Dosyayı varsayılan medya oynatıcıda açar."""
|
|
||||||
if not file_path or not os.path.exists(file_path):
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
if sys.platform == "win32":
|
|
||||||
os.startfile(file_path)
|
|
||||||
else:
|
|
||||||
subprocess.Popen(["xdg-open", file_path])
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
history = HistoryManager()
|
|
||||||
216
core/kick.py
|
|
@ -1,216 +0,0 @@
|
||||||
import re
|
|
||||||
import threading
|
|
||||||
from core.metadata import format_duration
|
|
||||||
|
|
||||||
_KICK_URL_RE = re.compile(
|
|
||||||
r"^https?://(?:www\.)?kick\.com/"
|
|
||||||
r"(?P<channel>[\w-]+)"
|
|
||||||
r"(?:(?P<rest>/videos/[\da-f-]+|/clips/clip_[\w-]+|/?\?(?:[^#]+&)?clip=clip_[\w-]+))?",
|
|
||||||
re.IGNORECASE
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_kick_input(raw_input: str) -> dict:
|
|
||||||
"""
|
|
||||||
Kullanıcı girdisini ayrıştırır:
|
|
||||||
- Kanal adı (örn: 'elraenn', '@xqc', 'https://kick.com/xqc') -> {'type': 'channel', 'channel': 'xqc', 'url': 'https://kick.com/xqc'}
|
|
||||||
- VOD URL -> {'type': 'vod', 'channel': '...', 'url': '...'}
|
|
||||||
- Clip URL -> {'type': 'clip', 'channel': '...', 'url': '...'}
|
|
||||||
"""
|
|
||||||
text = (raw_input or "").strip()
|
|
||||||
if not text:
|
|
||||||
return {"type": "empty", "channel": "", "url": ""}
|
|
||||||
|
|
||||||
# Doğrudan URL kontrolü
|
|
||||||
if text.startswith(("http://", "https://", "kick.com/", "www.kick.com/")):
|
|
||||||
if not text.startswith(("http://", "https://")):
|
|
||||||
text = "https://" + text
|
|
||||||
|
|
||||||
m = _KICK_URL_RE.match(text)
|
|
||||||
if m:
|
|
||||||
channel = m.group("channel").lower()
|
|
||||||
rest = (m.group("rest") or "").lower()
|
|
||||||
if "/videos/" in rest:
|
|
||||||
return {"type": "vod", "channel": channel, "url": text}
|
|
||||||
if "clip_" in rest:
|
|
||||||
return {"type": "clip", "channel": channel, "url": text}
|
|
||||||
if channel not in ("video", "categories", "search", "auth"):
|
|
||||||
return {"type": "channel", "channel": channel, "url": f"https://kick.com/{channel}"}
|
|
||||||
return {"type": "url", "channel": "", "url": text}
|
|
||||||
|
|
||||||
# Kanal kullanıcı adı (örn: 'xqc' veya '@xqc')
|
|
||||||
slug = text.lstrip("@").strip("/").split("/")[0].strip()
|
|
||||||
if re.match(r"^[\w-]+$", slug):
|
|
||||||
return {"type": "channel", "channel": slug.lower(), "url": f"https://kick.com/{slug.lower()}"}
|
|
||||||
|
|
||||||
return {"type": "unknown", "channel": "", "url": text}
|
|
||||||
|
|
||||||
|
|
||||||
def _kick_api_get(endpoint: str, proxy: str = None, timeout: int = 15):
|
|
||||||
"""
|
|
||||||
Kick API v2 endpoint'ine Cloudflare TLS parmak izi (impersonate) ile istek atar.
|
|
||||||
Öncelikle curl_cffi kullanır, yoksa yt_dlp üzerinden fallback yapar.
|
|
||||||
"""
|
|
||||||
url = f"https://kick.com/api/{endpoint.lstrip('/')}"
|
|
||||||
headers = {
|
|
||||||
"Accept": "application/json, text/plain, */*",
|
|
||||||
"Accept-Language": "tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
|
|
||||||
"Referer": "https://kick.com/",
|
|
||||||
}
|
|
||||||
|
|
||||||
# 1. Yöntem: curl_cffi (Chrome TLS Impersonation - Cloudflare Bypass)
|
|
||||||
try:
|
|
||||||
from curl_cffi import requests as creq
|
|
||||||
proxies = {"http": proxy, "https": proxy} if proxy else None
|
|
||||||
resp = creq.get(
|
|
||||||
url,
|
|
||||||
headers=headers,
|
|
||||||
impersonate="chrome",
|
|
||||||
proxies=proxies,
|
|
||||||
timeout=timeout
|
|
||||||
)
|
|
||||||
if resp.status_code == 200:
|
|
||||||
return resp.json()
|
|
||||||
if resp.status_code == 404:
|
|
||||||
raise ValueError("Kick kanalı veya içerik bulunamadı (404).")
|
|
||||||
except ValueError:
|
|
||||||
raise
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# 2. Yöntem: yt_dlp içsel impersonate istemcisi
|
|
||||||
import yt_dlp
|
|
||||||
from yt_dlp.networking.impersonate import ImpersonateTarget
|
|
||||||
ydl_opts = {
|
|
||||||
"quiet": True,
|
|
||||||
"no_warnings": True,
|
|
||||||
"socket_timeout": timeout,
|
|
||||||
"impersonate": ImpersonateTarget.from_str("chrome"),
|
|
||||||
}
|
|
||||||
if proxy:
|
|
||||||
ydl_opts["proxy"] = proxy
|
|
||||||
|
|
||||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
||||||
return ydl._download_json(url, endpoint, note=False, headers=headers)
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_kick_channel_Async(channel_slug: str, proxy: str = None, callback=None, error_callback=None):
|
|
||||||
"""
|
|
||||||
Kick kanalının canlı yayın durumunu, geçmiş yayınlarını (VODs) ve kliplerini (Clips)
|
|
||||||
arka planda tek seferde çeker.
|
|
||||||
"""
|
|
||||||
slug = (channel_slug or "").strip().lstrip("@").lower()
|
|
||||||
if not slug:
|
|
||||||
if error_callback:
|
|
||||||
error_callback("Geçerli bir Kick kanal adı girin.")
|
|
||||||
return
|
|
||||||
|
|
||||||
def _worker():
|
|
||||||
try:
|
|
||||||
ch_data = _kick_api_get(f"v2/channels/{slug}", proxy=proxy)
|
|
||||||
if not ch_data or not isinstance(ch_data, dict):
|
|
||||||
raise ValueError(f"'{slug}' kanalı bulunamadı.")
|
|
||||||
|
|
||||||
user_obj = ch_data.get("user") or {}
|
|
||||||
username = user_obj.get("username") or ch_data.get("slug") or slug
|
|
||||||
followers = ch_data.get("followers_count") or 0
|
|
||||||
avatar_url = user_obj.get("profile_pic") or ""
|
|
||||||
|
|
||||||
livestream = ch_data.get("livestream")
|
|
||||||
is_live = bool(livestream and isinstance(livestream, dict))
|
|
||||||
live_info = None
|
|
||||||
if is_live:
|
|
||||||
cats = livestream.get("categories") or []
|
|
||||||
cat_name = cats[0].get("name", "Canlı Yayın") if cats and isinstance(cats[0], dict) else "Canlı Yayın"
|
|
||||||
thumb_obj = livestream.get("thumbnail")
|
|
||||||
thumb_url = thumb_obj.get("url") if isinstance(thumb_obj, dict) else (thumb_obj if isinstance(thumb_obj, str) else "")
|
|
||||||
live_info = {
|
|
||||||
"id": str(livestream.get("id") or slug),
|
|
||||||
"title": livestream.get("session_title") or f"{username} Canlı Yayını",
|
|
||||||
"viewers": livestream.get("viewer_count") or 0,
|
|
||||||
"category": cat_name,
|
|
||||||
"created_at": (livestream.get("created_at") or "")[:16].replace("T", " "),
|
|
||||||
"thumbnail": thumb_url,
|
|
||||||
"url": f"https://kick.com/{slug}",
|
|
||||||
}
|
|
||||||
|
|
||||||
# 2. VOD (Geçmiş Yayınlar) çek
|
|
||||||
vods_list = []
|
|
||||||
try:
|
|
||||||
raw_vods = _kick_api_get(f"v2/channels/{slug}/videos", proxy=proxy) or []
|
|
||||||
if isinstance(raw_vods, list):
|
|
||||||
for v in raw_vods:
|
|
||||||
if not isinstance(v, dict):
|
|
||||||
continue
|
|
||||||
vid_obj = v.get("video") or {}
|
|
||||||
uuid = vid_obj.get("uuid") or v.get("uuid")
|
|
||||||
if not uuid:
|
|
||||||
continue
|
|
||||||
dur_ms = v.get("duration") or 0
|
|
||||||
# Kick API VOD duration milisaniye cinsindendir
|
|
||||||
dur_sec = dur_ms / 1000.0 if dur_ms > 36000 else dur_ms
|
|
||||||
cats = v.get("categories") or []
|
|
||||||
cat_name = cats[0].get("name", "—") if cats and isinstance(cats[0], dict) else "—"
|
|
||||||
created_raw = (v.get("created_at") or v.get("start_time") or "")[:16].replace("T", " ")
|
|
||||||
vods_list.append({
|
|
||||||
"uuid": uuid,
|
|
||||||
"title": v.get("session_title") or "İsimsiz Yayın Tekrarı (VOD)",
|
|
||||||
"duration": format_duration(dur_sec),
|
|
||||||
"views": v.get("views") or 0,
|
|
||||||
"date": created_raw or "—",
|
|
||||||
"category": cat_name,
|
|
||||||
"is_live": bool(v.get("is_live")),
|
|
||||||
"url": f"https://kick.com/{slug}/videos/{uuid}",
|
|
||||||
})
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# 3. Klipleri (Clips) çek
|
|
||||||
clips_list = []
|
|
||||||
try:
|
|
||||||
raw_clips_resp = _kick_api_get(f"v2/channels/{slug}/clips", proxy=proxy) or {}
|
|
||||||
raw_clips = raw_clips_resp.get("clips") if isinstance(raw_clips_resp, dict) else []
|
|
||||||
if isinstance(raw_clips, list):
|
|
||||||
for c in raw_clips:
|
|
||||||
if not isinstance(c, dict):
|
|
||||||
continue
|
|
||||||
clip_id = c.get("id")
|
|
||||||
if not clip_id:
|
|
||||||
continue
|
|
||||||
cat_obj = c.get("category") or {}
|
|
||||||
creator_obj = c.get("creator") or {}
|
|
||||||
created_raw = (c.get("created_at") or "")[:16].replace("T", " ")
|
|
||||||
clips_list.append({
|
|
||||||
"id": clip_id,
|
|
||||||
"title": c.get("title") or "İsimsiz Klip",
|
|
||||||
"duration": format_duration(c.get("duration") or 0),
|
|
||||||
"views": c.get("view_count") if c.get("view_count") is not None else (c.get("views") or 0),
|
|
||||||
"likes": c.get("likes_count") if c.get("likes_count") is not None else (c.get("likes") or 0),
|
|
||||||
"creator": creator_obj.get("username") or slug,
|
|
||||||
"category": cat_obj.get("name") or "—",
|
|
||||||
"date": created_raw or "—",
|
|
||||||
"url": f"https://kick.com/{slug}/clips/{clip_id}",
|
|
||||||
})
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
result = {
|
|
||||||
"slug": slug,
|
|
||||||
"username": username,
|
|
||||||
"followers": followers,
|
|
||||||
"avatar_url": avatar_url,
|
|
||||||
"is_live": is_live,
|
|
||||||
"live_info": live_info,
|
|
||||||
"vods": vods_list,
|
|
||||||
"clips": clips_list,
|
|
||||||
"channel_url": f"https://kick.com/{slug}",
|
|
||||||
}
|
|
||||||
|
|
||||||
if callback:
|
|
||||||
callback(result)
|
|
||||||
|
|
||||||
except Exception as ex:
|
|
||||||
if error_callback:
|
|
||||||
error_callback(str(ex))
|
|
||||||
|
|
||||||
threading.Thread(target=_worker, daemon=True).start()
|
|
||||||
193
core/metadata.py
|
|
@ -1,193 +0,0 @@
|
||||||
import os
|
|
||||||
import io
|
|
||||||
import threading
|
|
||||||
import requests
|
|
||||||
from PIL import Image, ImageTk
|
|
||||||
from core.dependencies import find_executable
|
|
||||||
|
|
||||||
_METADATA_CACHE = {}
|
|
||||||
_CACHE_LOCK = threading.Lock()
|
|
||||||
_MAX_CACHE_SIZE = 64
|
|
||||||
_IN_FLIGHT = {}
|
|
||||||
|
|
||||||
def format_duration(seconds):
|
|
||||||
"""Saniyeyi ss:dd veya saat:ss:dd formatına dönüştürür."""
|
|
||||||
if not seconds:
|
|
||||||
return "—"
|
|
||||||
try:
|
|
||||||
s = int(seconds)
|
|
||||||
hours = s // 3600
|
|
||||||
minutes = (s % 3600) // 60
|
|
||||||
secs = s % 60
|
|
||||||
if hours > 0:
|
|
||||||
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
|
|
||||||
return f"{minutes:02d}:{secs:02d}"
|
|
||||||
except Exception:
|
|
||||||
return "—"
|
|
||||||
|
|
||||||
|
|
||||||
def extract_resolutions(info_dict):
|
|
||||||
"""Videonun format listesinden gerçek çözünürlükleri çıkarır."""
|
|
||||||
formats = info_dict.get("formats") or []
|
|
||||||
heights = set()
|
|
||||||
for f in formats:
|
|
||||||
# Sadece video içeren formatlar
|
|
||||||
if f.get("vcodec") != "none" and f.get("height"):
|
|
||||||
heights.add(int(f["height"]))
|
|
||||||
|
|
||||||
sorted_heights = sorted(list(heights), reverse=True)
|
|
||||||
res_list = ["Best Quality (En İyi)"]
|
|
||||||
for h in sorted_heights:
|
|
||||||
label = f"{h}p"
|
|
||||||
if h >= 2160:
|
|
||||||
label += " (4K)"
|
|
||||||
elif h >= 1440:
|
|
||||||
label += " (2K)"
|
|
||||||
elif h >= 1080:
|
|
||||||
label += " (FHD)"
|
|
||||||
elif h >= 720:
|
|
||||||
label += " (HD)"
|
|
||||||
res_list.append(label)
|
|
||||||
|
|
||||||
return res_list
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_thumbnail_image(url, size=(160, 90)):
|
|
||||||
"""Thumbnail URL'sinden resmi çeker ve belirtilen boyutta PIL Image döndürür."""
|
|
||||||
if not url:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
|
|
||||||
resp = requests.get(url, headers=headers, timeout=10)
|
|
||||||
if resp.status_code != 200 and "kick.com" in url:
|
|
||||||
try:
|
|
||||||
from curl_cffi import requests as creq
|
|
||||||
resp = creq.get(url, impersonate="chrome", timeout=10)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if resp.status_code == 200:
|
|
||||||
img_data = resp.content
|
|
||||||
img = Image.open(io.BytesIO(img_data))
|
|
||||||
img = img.convert("RGBA")
|
|
||||||
img = img.resize(size, Image.Resampling.LANCZOS)
|
|
||||||
return img
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_video_metadata(url: str, cookies_args: list = None, proxy: str = None, callback=None, error_callback=None):
|
|
||||||
"""Videonun temel bilgilerini arka planda çeker (önbellek ve istek tekilleştirme destekli)."""
|
|
||||||
clean_url = (url or "").strip()
|
|
||||||
if not clean_url:
|
|
||||||
if error_callback:
|
|
||||||
error_callback("Geçersiz URL")
|
|
||||||
return
|
|
||||||
|
|
||||||
with _CACHE_LOCK:
|
|
||||||
if clean_url in _METADATA_CACHE:
|
|
||||||
cached = _METADATA_CACHE[clean_url]
|
|
||||||
if callback:
|
|
||||||
# Önbellekteki veriyi anında döndür
|
|
||||||
threading.Thread(target=lambda: callback(cached), daemon=True).start()
|
|
||||||
return
|
|
||||||
|
|
||||||
if clean_url in _IN_FLIGHT:
|
|
||||||
_IN_FLIGHT[clean_url].append((callback, error_callback))
|
|
||||||
return
|
|
||||||
|
|
||||||
_IN_FLIGHT[clean_url] = [(callback, error_callback)]
|
|
||||||
|
|
||||||
def _worker():
|
|
||||||
try:
|
|
||||||
import yt_dlp
|
|
||||||
ydl_opts = {
|
|
||||||
'quiet': True,
|
|
||||||
'no_warnings': True,
|
|
||||||
'extract_flat': 'in_playlist',
|
|
||||||
'skip_download': True,
|
|
||||||
'socket_timeout': 15,
|
|
||||||
}
|
|
||||||
if proxy:
|
|
||||||
ydl_opts['proxy'] = proxy
|
|
||||||
|
|
||||||
if cookies_args:
|
|
||||||
# Cookies args parse (örnek: --cookies-from-browser firefox[:profile] veya --cookies file)
|
|
||||||
for i, arg in enumerate(cookies_args):
|
|
||||||
if arg == "--cookies-from-browser" and i + 1 < len(cookies_args):
|
|
||||||
spec = cookies_args[i + 1]
|
|
||||||
if ":" in spec:
|
|
||||||
b_name, b_prof = spec.split(":", 1)
|
|
||||||
ydl_opts['cookiesfrombrowser'] = (b_name, b_prof)
|
|
||||||
else:
|
|
||||||
ydl_opts['cookiesfrombrowser'] = (spec,)
|
|
||||||
elif arg == "--cookies" and i + 1 < len(cookies_args):
|
|
||||||
ydl_opts['cookiefile'] = cookies_args[i + 1]
|
|
||||||
|
|
||||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
||||||
info = ydl.extract_info(clean_url, download=False)
|
|
||||||
if not info:
|
|
||||||
raise ValueError("Medya bilgileri alınamadı.")
|
|
||||||
|
|
||||||
is_playlist = info.get('_type') == 'playlist' or 'entries' in info
|
|
||||||
entries = list(info.get('entries') or []) if is_playlist else []
|
|
||||||
first_entry = entries[0] if (is_playlist and entries and isinstance(entries[0], dict)) else info
|
|
||||||
|
|
||||||
title = first_entry.get("title") or info.get("title") or "Bilinmeyen Başlık"
|
|
||||||
uploader = (
|
|
||||||
first_entry.get("uploader")
|
|
||||||
or first_entry.get("channel")
|
|
||||||
or info.get("uploader")
|
|
||||||
or info.get("channel")
|
|
||||||
or "Bilinmeyen Kanal"
|
|
||||||
)
|
|
||||||
is_live = bool(first_entry.get("is_live") or info.get("is_live"))
|
|
||||||
duration = "🔴 CANLI YAYIN" if is_live else format_duration(first_entry.get("duration") or info.get("duration"))
|
|
||||||
thumbnail_url = first_entry.get("thumbnail") or info.get("thumbnail")
|
|
||||||
if not thumbnail_url:
|
|
||||||
thumbs = first_entry.get("thumbnails") or info.get("thumbnails") or []
|
|
||||||
if thumbs and isinstance(thumbs, list):
|
|
||||||
thumbnail_url = thumbs[-1].get("url")
|
|
||||||
|
|
||||||
resolutions = extract_resolutions(first_entry)
|
|
||||||
thumb_img = fetch_thumbnail_image(thumbnail_url)
|
|
||||||
|
|
||||||
metadata = {
|
|
||||||
"is_playlist": is_playlist,
|
|
||||||
"is_live": is_live,
|
|
||||||
"playlist_count": len(entries) if is_playlist else 1,
|
|
||||||
"title": title,
|
|
||||||
"uploader": uploader,
|
|
||||||
"duration": duration,
|
|
||||||
"thumbnail_url": thumbnail_url,
|
|
||||||
"thumbnail_img": thumb_img,
|
|
||||||
"resolutions": resolutions,
|
|
||||||
"raw_info": first_entry
|
|
||||||
}
|
|
||||||
|
|
||||||
with _CACHE_LOCK:
|
|
||||||
if len(_METADATA_CACHE) >= _MAX_CACHE_SIZE:
|
|
||||||
# En eski kaydı temizle
|
|
||||||
_METADATA_CACHE.pop(next(iter(_METADATA_CACHE)))
|
|
||||||
_METADATA_CACHE[clean_url] = metadata
|
|
||||||
listeners = _IN_FLIGHT.pop(clean_url, [])
|
|
||||||
|
|
||||||
for cb, _ in listeners:
|
|
||||||
if cb:
|
|
||||||
try:
|
|
||||||
cb(metadata)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
except Exception as ex:
|
|
||||||
err_msg = str(ex)
|
|
||||||
with _CACHE_LOCK:
|
|
||||||
listeners = _IN_FLIGHT.pop(clean_url, [])
|
|
||||||
for _, err_cb in listeners:
|
|
||||||
if err_cb:
|
|
||||||
try:
|
|
||||||
err_cb(err_msg)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
threading.Thread(target=_worker, daemon=True).start()
|
|
||||||
13
index.html
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="tr" class="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/png" href="/logo.png" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>LDownloader</title>
|
||||||
|
</head>
|
||||||
|
<body class="bg-titanium-900 text-steel-text select-none overflow-hidden m-0 p-0 font-sans">
|
||||||
|
<div id="root" class="h-screen w-screen flex flex-col overflow-hidden"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
; Inno Setup Kurulum Senaryosu - LDownloader
|
|
||||||
#define MyAppName "LDownloader"
|
|
||||||
#define MyAppVersion "3.6.0"
|
|
||||||
#define MyAppPublisher "LilDosto"
|
|
||||||
#define MyAppURL "https://ttmadethat.shop"
|
|
||||||
#define MyAppExeName "LDownloader.exe"
|
|
||||||
|
|
||||||
[Setup]
|
|
||||||
; Benzersiz Uygulama Kimligi (GUID)
|
|
||||||
AppId={{5E4B4C3E-91C0-46EA-B882-9BE8B85BD14B}
|
|
||||||
AppName={#MyAppName}
|
|
||||||
AppVersion={#MyAppVersion}
|
|
||||||
AppPublisher={#MyAppPublisher}
|
|
||||||
AppPublisherURL={#MyAppURL}
|
|
||||||
AppSupportURL={#MyAppURL}
|
|
||||||
AppUpdatesURL={#MyAppURL}
|
|
||||||
DefaultDirName={autopf}\{#MyAppName}
|
|
||||||
DisableProgramGroupPage=yes
|
|
||||||
LicenseFile=LICENSE
|
|
||||||
PrivilegesRequired=admin
|
|
||||||
PrivilegesRequiredOverridesAllowed=dialog
|
|
||||||
OutputDir=dist
|
|
||||||
OutputBaseFilename=LDownloader-v{#MyAppVersion}-Setup
|
|
||||||
SetupIconFile=assets\logo.ico
|
|
||||||
UninstallDisplayIcon={app}\assets\ld_v36_icon.ico
|
|
||||||
ChangesAssociations=yes
|
|
||||||
CloseApplications=force
|
|
||||||
Compression=lzma2/ultra64
|
|
||||||
SolidCompression=yes
|
|
||||||
WizardStyle=modern
|
|
||||||
|
|
||||||
[Languages]
|
|
||||||
Name: "turkish"; MessagesFile: "compiler:Languages\Turkish.isl"
|
|
||||||
Name: "english"; MessagesFile: "compiler:Default.isl"
|
|
||||||
|
|
||||||
[Tasks]
|
|
||||||
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"
|
|
||||||
|
|
||||||
[InstallDelete]
|
|
||||||
Type: files; Name: "{autodesktop}\{#MyAppName}.lnk"
|
|
||||||
Type: files; Name: "{userdesktop}\{#MyAppName}.lnk"
|
|
||||||
Type: files; Name: "{commondesktop}\{#MyAppName}.lnk"
|
|
||||||
Type: files; Name: "{autoprograms}\{#MyAppName}.lnk"
|
|
||||||
|
|
||||||
[Files]
|
|
||||||
Source: "dist\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion
|
|
||||||
Source: "assets\logo.ico"; DestDir: "{app}\assets"; Flags: ignoreversion
|
|
||||||
Source: "assets\logo.ico"; DestDir: "{app}\assets"; DestName: "ld_v36_icon.ico"; Flags: ignoreversion
|
|
||||||
Source: "LICENSE"; DestDir: "{app}"; Flags: ignoreversion
|
|
||||||
|
|
||||||
[Icons]
|
|
||||||
Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; IconFilename: "{app}\assets\ld_v36_icon.ico"; AppUserModelID: "LilDosto.LDownloader.App.v36"
|
|
||||||
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; IconFilename: "{app}\assets\ld_v36_icon.ico"; AppUserModelID: "LilDosto.LDownloader.App.v36"; Tasks: desktopicon
|
|
||||||
|
|
||||||
[Run]
|
|
||||||
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
|
|
||||||
12
kur.bat
|
|
@ -1,12 +0,0 @@
|
||||||
@echo off
|
|
||||||
chcp 65001 >nul
|
|
||||||
echo [LDownloader v3.6.0] Kurulum ve İkon Önbelleği Yenileme Başlatılıyor...
|
|
||||||
taskkill /f /im LDownloader.exe >nul 2>&1
|
|
||||||
"%~dp0dist\LDownloader-v3.6.0-Setup.exe" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /MERGETASKS="desktopicon"
|
|
||||||
ie4uinit.exe -show
|
|
||||||
echo Tamamlandı! Uygulama başlatılıyor...
|
|
||||||
if exist "C:\Program Files (x86)\LDownloader\LDownloader.exe" (
|
|
||||||
start "" "C:\Program Files (x86)\LDownloader\LDownloader.exe"
|
|
||||||
) else if exist "%LOCALAPPDATA%\Programs\LDownloader\LDownloader.exe" (
|
|
||||||
start "" "%LOCALAPPDATA%\Programs\LDownloader\LDownloader.exe"
|
|
||||||
)
|
|
||||||
31
main.py
|
|
@ -1,31 +0,0 @@
|
||||||
"""LDownloader v3 — Video & Ses İndirici Ana Başlatıcı"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
root_dir = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
if root_dir not in sys.path:
|
|
||||||
sys.path.insert(0, root_dir)
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
from ui.app import main
|
|
||||||
main()
|
|
||||||
except Exception as ex:
|
|
||||||
import traceback
|
|
||||||
log_path = "crash.log"
|
|
||||||
try:
|
|
||||||
from core.config import get_data_dir
|
|
||||||
log_path = os.path.join(get_data_dir(), "crash.log")
|
|
||||||
with open(log_path, "w", encoding="utf-8") as f:
|
|
||||||
traceback.print_exc(file=f)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
import tkinter as tk
|
|
||||||
from tkinter import messagebox
|
|
||||||
root = tk.Tk()
|
|
||||||
root.withdraw()
|
|
||||||
messagebox.showerror(
|
|
||||||
"LDownloader Başlatma Hatası",
|
|
||||||
f"Uygulama başlatılırken bir hata oluştu:\n\n{ex}\n\nDetaylar: {log_path}"
|
|
||||||
)
|
|
||||||
sys.exit(1)
|
|
||||||
3190
package-lock.json
generated
Normal file
39
package.json
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
{
|
||||||
|
"name": "ldownloader",
|
||||||
|
"private": true,
|
||||||
|
"version": "3.6.0",
|
||||||
|
"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-opener": "^2.2.5",
|
||||||
|
"@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",
|
||||||
|
"lucide-react": "^0.474.0",
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-dom": "^18.3.1",
|
||||||
|
"tailwind-merge": "^3.0.1",
|
||||||
|
"zustand": "^5.0.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tauri-apps/cli": "^2.2.0",
|
||||||
|
"@types/node": "^22.13.1",
|
||||||
|
"@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.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
6
postcss.config.js
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
BIN
public/logo.png
Normal file
|
After Width: | Height: | Size: 347 KiB |
|
|
@ -1,5 +0,0 @@
|
||||||
yt-dlp[default]>=2024.8.0
|
|
||||||
yt-dlp-ejs>=0.8.0
|
|
||||||
pillow>=10.0.0
|
|
||||||
requests>=2.28.0
|
|
||||||
pyinstaller>=6.0.0
|
|
||||||
6108
src-tauri/Cargo.lock
generated
Normal file
43
src-tauri/Cargo.toml
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
[package]
|
||||||
|
name = "ldownloader"
|
||||||
|
version = "3.6.0"
|
||||||
|
description = "LDownloader - Ultra-fast media downloader for Windows (Tauri v2, Rust, React)"
|
||||||
|
authors = ["LilDosto"]
|
||||||
|
license = "MIT"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "ldownloader_lib"
|
||||||
|
crate-type = ["staticlib", "rlib"]
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
tauri-build = { version = "2.0.5", features = [] }
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tauri = { version = "2.2.0", features = ["tray-icon"] }
|
||||||
|
tauri-plugin-dialog = "2"
|
||||||
|
tauri-plugin-fs = "2"
|
||||||
|
tauri-plugin-opener = "2"
|
||||||
|
tauri-plugin-process = "2"
|
||||||
|
tauri-plugin-shell = "2"
|
||||||
|
tauri-plugin-single-instance = "2"
|
||||||
|
tauri-plugin-updater = "2"
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1.0"
|
||||||
|
tokio = { version = "1.42", features = ["full"] }
|
||||||
|
thiserror = "2.0"
|
||||||
|
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }
|
||||||
|
regex = "1.11"
|
||||||
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
|
zip = { version = "2.2", default-features = false, features = ["deflate"] }
|
||||||
|
futures-util = "0.3"
|
||||||
|
directories = "5.0"
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
windows-sys = { version = "0.59", features = [
|
||||||
|
"Win32_Foundation",
|
||||||
|
"Win32_UI_WindowsAndMessaging",
|
||||||
|
"Win32_UI_Shell",
|
||||||
|
"Win32_System_Threading",
|
||||||
|
"Win32_Storage_FileSystem"
|
||||||
|
] }
|
||||||
3
src-tauri/build.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
fn main() {
|
||||||
|
tauri_build::build();
|
||||||
|
}
|
||||||
22
src-tauri/capabilities/default.json
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://schema.tauri.app/config/2/capability",
|
||||||
|
"identifier": "default",
|
||||||
|
"description": "Default permissions for LDownloader",
|
||||||
|
"windows": ["main"],
|
||||||
|
"permissions": [
|
||||||
|
"core:default",
|
||||||
|
"core:window:allow-start-dragging",
|
||||||
|
"core:window:allow-close",
|
||||||
|
"core:window:allow-minimize",
|
||||||
|
"core:window:allow-maximize",
|
||||||
|
"core:window:allow-unmaximize",
|
||||||
|
"core:window:allow-is-maximized",
|
||||||
|
"dialog:default",
|
||||||
|
"dialog:allow-open",
|
||||||
|
"opener:default",
|
||||||
|
"opener:allow-open-path",
|
||||||
|
"opener:allow-open-url",
|
||||||
|
"updater:default",
|
||||||
|
"process: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":"Default permissions for LDownloader","local":true,"windows":["main"],"permissions":["core:default","core:window:allow-start-dragging","core:window:allow-close","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-is-maximized","dialog:default","dialog:allow-open","opener:default","opener:allow-open-path","opener:allow-open-url","updater:default","process:default"]}}
|
||||||
6595
src-tauri/gen/schemas/desktop-schema.json
Normal file
6595
src-tauri/gen/schemas/windows-schema.json
Normal file
BIN
src-tauri/icons/128x128.png
Normal file
|
After Width: | Height: | Size: 27 KiB |
BIN
src-tauri/icons/128x128@2x.png
Normal file
|
After Width: | Height: | Size: 93 KiB |
BIN
src-tauri/icons/32x32.png
Normal file
|
After Width: | Height: | Size: 2.6 KiB |
BIN
src-tauri/icons/64x64.png
Normal file
|
After Width: | Height: | Size: 8.4 KiB |
BIN
src-tauri/icons/Square107x107Logo.png
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
src-tauri/icons/Square142x142Logo.png
Normal file
|
After Width: | Height: | Size: 32 KiB |
BIN
src-tauri/icons/Square150x150Logo.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
BIN
src-tauri/icons/Square284x284Logo.png
Normal file
|
After Width: | Height: | Size: 113 KiB |
BIN
src-tauri/icons/Square30x30Logo.png
Normal file
|
After Width: | Height: | Size: 2.4 KiB |
BIN
src-tauri/icons/Square310x310Logo.png
Normal file
|
After Width: | Height: | Size: 133 KiB |
BIN
src-tauri/icons/Square44x44Logo.png
Normal file
|
After Width: | Height: | Size: 4.5 KiB |
BIN
src-tauri/icons/Square71x71Logo.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
src-tauri/icons/Square89x89Logo.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
src-tauri/icons/StoreLogo.png
Normal file
|
After Width: | Height: | Size: 5.5 KiB |
|
|
@ -0,0 +1,5 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||||
|
<background android:drawable="@color/ic_launcher_background"/>
|
||||||
|
</adaptive-icon>
|
||||||
BIN
src-tauri/icons/android/mipmap-hdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 8 KiB |
BIN
src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 7.6 KiB |
BIN
src-tauri/icons/android/mipmap-mdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 4.1 KiB |
BIN
src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 3.9 KiB |
BIN
src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 68 KiB |
BIN
src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 26 KiB |
BIN
src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 144 KiB |
BIN
src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 250 KiB |
BIN
src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 40 KiB |
|
|
@ -0,0 +1,4 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<color name="ic_launcher_background">#FFFFFF</color>
|
||||||
|
</resources>
|
||||||
BIN
src-tauri/icons/icon.icns
Normal file
BIN
src-tauri/icons/icon.ico
Normal file
|
After Width: | Height: | Size: 113 KiB |
BIN
src-tauri/icons/icon.png
Normal file
|
After Width: | Height: | Size: 338 KiB |
BIN
src-tauri/icons/ios/AppIcon-20x20@1x.png
Normal file
|
After Width: | Height: | Size: 1.2 KiB |
BIN
src-tauri/icons/ios/AppIcon-20x20@2x-1.png
Normal file
|
After Width: | Height: | Size: 3.7 KiB |
BIN
src-tauri/icons/ios/AppIcon-20x20@2x.png
Normal file
|
After Width: | Height: | Size: 3.7 KiB |
BIN
src-tauri/icons/ios/AppIcon-20x20@3x.png
Normal file
|
After Width: | Height: | Size: 7.3 KiB |
BIN
src-tauri/icons/ios/AppIcon-29x29@1x.png
Normal file
|
After Width: | Height: | Size: 2.2 KiB |
BIN
src-tauri/icons/ios/AppIcon-29x29@2x-1.png
Normal file
|
After Width: | Height: | Size: 6.9 KiB |
BIN
src-tauri/icons/ios/AppIcon-29x29@2x.png
Normal file
|
After Width: | Height: | Size: 6.9 KiB |
BIN
src-tauri/icons/ios/AppIcon-29x29@3x.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
src-tauri/icons/ios/AppIcon-40x40@1x.png
Normal file
|
After Width: | Height: | Size: 3.7 KiB |
BIN
src-tauri/icons/ios/AppIcon-40x40@2x-1.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
src-tauri/icons/ios/AppIcon-40x40@2x.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
src-tauri/icons/ios/AppIcon-40x40@3x.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
src-tauri/icons/ios/AppIcon-512@2x.png
Normal file
|
After Width: | Height: | Size: 923 KiB |
BIN
src-tauri/icons/ios/AppIcon-60x60@2x.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
src-tauri/icons/ios/AppIcon-60x60@3x.png
Normal file
|
After Width: | Height: | Size: 47 KiB |
BIN
src-tauri/icons/ios/AppIcon-76x76@1x.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
src-tauri/icons/ios/AppIcon-76x76@2x.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
BIN
src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png
Normal file
|
After Width: | Height: | Size: 41 KiB |
19
src-tauri/src/commands/config.rs
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
use tauri::State;
|
||||||
|
use crate::error::AppError;
|
||||||
|
use crate::models::AppConfig;
|
||||||
|
use crate::services::config_service::save_config;
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
#[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(state: State<'_, AppState>, new_config: AppConfig) -> Result<(), AppError> {
|
||||||
|
save_config(&new_config)?;
|
||||||
|
let mut cfg = state.config.write().await;
|
||||||
|
*cfg = new_config;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
52
src-tauri/src/commands/dependencies.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
use tauri::{AppHandle, Emitter};
|
||||||
|
use crate::error::AppError;
|
||||||
|
use crate::models::DependencyStatus;
|
||||||
|
use crate::services::dependency_service::{check_dependencies as check_deps, install_deno as inst_deno, install_ffmpeg as inst_ffmpeg, install_ytdlp as inst_ytdlp};
|
||||||
|
|
||||||
|
#[derive(Clone, serde::Serialize)]
|
||||||
|
struct DepProgressPayload {
|
||||||
|
name: String,
|
||||||
|
percent: f32,
|
||||||
|
message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn check_dependencies() -> Result<DependencyStatus, AppError> {
|
||||||
|
Ok(check_deps().await)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn install_ytdlp(app: AppHandle) -> Result<String, AppError> {
|
||||||
|
let app_clone = app.clone();
|
||||||
|
inst_ytdlp(move |pct, msg| {
|
||||||
|
let _ = app_clone.emit("dep-install-progress", DepProgressPayload {
|
||||||
|
name: "yt-dlp".to_string(),
|
||||||
|
percent: pct,
|
||||||
|
message: msg.to_string(),
|
||||||
|
});
|
||||||
|
}).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn install_ffmpeg(app: AppHandle) -> Result<String, AppError> {
|
||||||
|
let app_clone = app.clone();
|
||||||
|
inst_ffmpeg(move |pct, msg| {
|
||||||
|
let _ = app_clone.emit("dep-install-progress", DepProgressPayload {
|
||||||
|
name: "ffmpeg".to_string(),
|
||||||
|
percent: pct,
|
||||||
|
message: msg.to_string(),
|
||||||
|
});
|
||||||
|
}).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn install_deno(app: AppHandle) -> Result<String, AppError> {
|
||||||
|
let app_clone = app.clone();
|
||||||
|
inst_deno(move |pct, msg| {
|
||||||
|
let _ = app_clone.emit("dep-install-progress", DepProgressPayload {
|
||||||
|
name: "deno".to_string(),
|
||||||
|
percent: pct,
|
||||||
|
message: msg.to_string(),
|
||||||
|
});
|
||||||
|
}).await
|
||||||
|
}
|
||||||
27
src-tauri/src/commands/diagnostics.rs
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
use tauri::State;
|
||||||
|
use crate::error::AppError;
|
||||||
|
use crate::models::AppConfig;
|
||||||
|
use crate::services::config_service::save_config;
|
||||||
|
use crate::services::logger_service::{generate_diagnostics_report, open_log_folder as svc_open_log_folder};
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn get_diagnostic_report() -> Result<String, AppError> {
|
||||||
|
generate_diagnostics_report()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn open_log_folder() -> Result<(), AppError> {
|
||||||
|
svc_open_log_folder()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn reset_config_to_defaults(state: State<'_, AppState>) -> Result<AppConfig, AppError> {
|
||||||
|
let default_config = AppConfig::default();
|
||||||
|
save_config(&default_config)?;
|
||||||
|
{
|
||||||
|
let mut guard = state.config.write().await;
|
||||||
|
*guard = default_config.clone();
|
||||||
|
}
|
||||||
|
Ok(default_config)
|
||||||
|
}
|
||||||
25
src-tauri/src/commands/download.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
use tauri::{AppHandle, State};
|
||||||
|
use crate::error::AppError;
|
||||||
|
use crate::models::DownloadRequest;
|
||||||
|
use crate::services::downloader_service::{cancel_download as svc_cancel_download, execute_download};
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn start_download(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
request: DownloadRequest,
|
||||||
|
) -> Result<(), AppError> {
|
||||||
|
let cfg = {
|
||||||
|
let guard = state.config.read().await;
|
||||||
|
guard.clone()
|
||||||
|
};
|
||||||
|
let active_map = state.active_processes.clone();
|
||||||
|
|
||||||
|
execute_download(app, request, cfg, active_map).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn cancel_download(state: State<'_, AppState>, id: String) -> Result<(), AppError> {
|
||||||
|
svc_cancel_download(&id, state.active_processes.clone()).await
|
||||||
|
}
|
||||||
32
src-tauri/src/commands/history.rs
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
use crate::error::AppError;
|
||||||
|
use crate::models::HistoryItem;
|
||||||
|
use crate::services::history_service::{
|
||||||
|
clear_history as svc_clear_history, load_history as svc_load_history,
|
||||||
|
remove_history_item as svc_remove_history_item,
|
||||||
|
};
|
||||||
|
use crate::services::system_service::{open_file as svc_open_file, show_in_folder as svc_show_in_folder};
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn get_history() -> Result<Vec<HistoryItem>, AppError> {
|
||||||
|
svc_load_history()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn remove_history_item(id: String) -> Result<(), AppError> {
|
||||||
|
svc_remove_history_item(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn clear_history() -> Result<(), AppError> {
|
||||||
|
svc_clear_history()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn open_history_file(path: String) -> Result<(), AppError> {
|
||||||
|
svc_open_file(&path)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn show_history_in_folder(path: String) -> Result<(), AppError> {
|
||||||
|
svc_show_in_folder(&path)
|
||||||
|
}
|
||||||
8
src-tauri/src/commands/kick.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
use crate::error::AppError;
|
||||||
|
use crate::models::KickDiscoveryResponse;
|
||||||
|
use crate::services::kick_service::discover_kick as svc_discover_kick;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn discover_kick(input: String) -> Result<KickDiscoveryResponse, AppError> {
|
||||||
|
svc_discover_kick(&input).await
|
||||||
|
}
|
||||||
14
src-tauri/src/commands/metadata.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
use tauri::State;
|
||||||
|
use crate::error::AppError;
|
||||||
|
use crate::models::MediaMetadata;
|
||||||
|
use crate::services::metadata_service::fetch_metadata as svc_fetch_metadata;
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn fetch_metadata(state: State<'_, AppState>, url: String) -> Result<MediaMetadata, AppError> {
|
||||||
|
let cfg = {
|
||||||
|
let guard = state.config.read().await;
|
||||||
|
guard.clone()
|
||||||
|
};
|
||||||
|
svc_fetch_metadata(&url, &cfg).await
|
||||||
|
}
|
||||||
7
src-tauri/src/commands/mod.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
pub mod config;
|
||||||
|
pub mod dependencies;
|
||||||
|
pub mod diagnostics;
|
||||||
|
pub mod download;
|
||||||
|
pub mod history;
|
||||||
|
pub mod kick;
|
||||||
|
pub mod metadata;
|
||||||
59
src-tauri/src/error.rs
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
use serde::Serialize;
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
pub enum AppError {
|
||||||
|
#[error("G/Ç Hatası: {0}")]
|
||||||
|
Io(String),
|
||||||
|
|
||||||
|
#[error("Ağ Hatası: {0}")]
|
||||||
|
Network(String),
|
||||||
|
|
||||||
|
#[error("Süreç Hatası: {0}")]
|
||||||
|
Process(String),
|
||||||
|
|
||||||
|
#[error("Bulunamadı: {0}")]
|
||||||
|
NotFound(String),
|
||||||
|
|
||||||
|
#[error("Geçersiz Girdi: {0}")]
|
||||||
|
InvalidInput(String),
|
||||||
|
|
||||||
|
#[error("JSON Serileştirme Hatası: {0}")]
|
||||||
|
Json(String),
|
||||||
|
|
||||||
|
#[error("İndirme Hatası: {0}")]
|
||||||
|
DownloadFailed(String),
|
||||||
|
|
||||||
|
#[error("İşlem kullanıcı tarafından iptal edildi")]
|
||||||
|
Cancelled,
|
||||||
|
|
||||||
|
#[error("Dahili Sistem Hatası: {0}")]
|
||||||
|
Internal(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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<std::io::Error> for AppError {
|
||||||
|
fn from(err: std::io::Error) -> Self {
|
||||||
|
AppError::Io(err.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<reqwest::Error> for AppError {
|
||||||
|
fn from(err: reqwest::Error) -> Self {
|
||||||
|
AppError::Network(err.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<serde_json::Error> for AppError {
|
||||||
|
fn from(err: serde_json::Error) -> Self {
|
||||||
|
AppError::Json(err.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
85
src-tauri/src/lib.rs
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
pub mod commands;
|
||||||
|
pub mod error;
|
||||||
|
pub mod models;
|
||||||
|
pub mod services;
|
||||||
|
pub mod state;
|
||||||
|
|
||||||
|
use services::config_service::load_config;
|
||||||
|
use state::AppState;
|
||||||
|
use tauri::Manager;
|
||||||
|
|
||||||
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
|
pub fn run() {
|
||||||
|
let initial_config = load_config().unwrap_or_default();
|
||||||
|
let app_state = AppState::new(initial_config);
|
||||||
|
|
||||||
|
services::logger_service::log("info", "APP", "LDownloader v3.6.0 başlatıldı");
|
||||||
|
|
||||||
|
let app = tauri::Builder::default()
|
||||||
|
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||||||
|
if let Some(w) = app.get_webview_window("main") {
|
||||||
|
let _ = w.unminimize();
|
||||||
|
let _ = w.show();
|
||||||
|
let _ = w.set_focus();
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.plugin(tauri_plugin_opener::init())
|
||||||
|
.plugin(tauri_plugin_dialog::init())
|
||||||
|
.plugin(tauri_plugin_fs::init())
|
||||||
|
.plugin(tauri_plugin_process::init())
|
||||||
|
.plugin(tauri_plugin_shell::init())
|
||||||
|
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||||
|
.manage(app_state)
|
||||||
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
commands::config::get_config,
|
||||||
|
commands::config::update_config,
|
||||||
|
commands::dependencies::check_dependencies,
|
||||||
|
commands::dependencies::install_ytdlp,
|
||||||
|
commands::dependencies::install_ffmpeg,
|
||||||
|
commands::dependencies::install_deno,
|
||||||
|
commands::metadata::fetch_metadata,
|
||||||
|
commands::download::start_download,
|
||||||
|
commands::download::cancel_download,
|
||||||
|
commands::kick::discover_kick,
|
||||||
|
commands::history::get_history,
|
||||||
|
commands::history::remove_history_item,
|
||||||
|
commands::history::clear_history,
|
||||||
|
commands::history::open_history_file,
|
||||||
|
commands::history::show_history_in_folder,
|
||||||
|
commands::diagnostics::get_diagnostic_report,
|
||||||
|
commands::diagnostics::open_log_folder,
|
||||||
|
commands::diagnostics::reset_config_to_defaults,
|
||||||
|
])
|
||||||
|
.build(tauri::generate_context!())
|
||||||
|
.expect("Tauri uygulaması başlatılamadı");
|
||||||
|
|
||||||
|
app.run(|app_handle, event| {
|
||||||
|
if let tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit = event {
|
||||||
|
services::logger_service::log("info", "APP", "LDownloader kapatılıyor, süreçler temizlendi");
|
||||||
|
// Kill any remaining child processes (yt-dlp, ffmpeg) on exit to prevent zombies
|
||||||
|
if let Some(state) = app_handle.try_state::<AppState>() {
|
||||||
|
let pids: Vec<u32> = {
|
||||||
|
let map = state.active_processes.blocking_lock();
|
||||||
|
map.values().filter_map(|p| p.child_id).collect()
|
||||||
|
};
|
||||||
|
|
||||||
|
for pid in pids {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
let _ = std::process::Command::new("taskkill")
|
||||||
|
.args(["/F", "/T", "/PID", &pid.to_string()])
|
||||||
|
.creation_flags(0x08000000)
|
||||||
|
.output();
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
let _ = std::process::Command::new("kill")
|
||||||
|
.args(["-9", &pid.to_string()])
|
||||||
|
.output();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
6
src-tauri/src/main.rs
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||||
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
ldownloader_lib::run();
|
||||||
|
}
|
||||||
88
src-tauri/src/models/config.rs
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct AppConfig {
|
||||||
|
pub theme: String,
|
||||||
|
pub download_dir: String,
|
||||||
|
pub video_format: String,
|
||||||
|
pub video_quality: String,
|
||||||
|
pub audio_format: String,
|
||||||
|
pub audio_quality: String,
|
||||||
|
pub cookies_mode: String,
|
||||||
|
pub cookies_browser: String,
|
||||||
|
pub cookies_path: String,
|
||||||
|
pub embed_subtitles: bool,
|
||||||
|
pub subtitle_lang: String,
|
||||||
|
pub embed_thumbnail: bool,
|
||||||
|
pub add_metadata: bool,
|
||||||
|
pub concurrent_fragments: u32,
|
||||||
|
pub speed_limit: String,
|
||||||
|
pub proxy: String,
|
||||||
|
pub ignore_errors: bool,
|
||||||
|
pub sponsorblock_remove: bool,
|
||||||
|
pub sponsorblock_cats: String,
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub auto_update_on_startup: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_true() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for AppConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
let download_dir = directories::UserDirs::new()
|
||||||
|
.and_then(|dirs| dirs.download_dir().map(|p| p.to_string_lossy().to_string()))
|
||||||
|
.unwrap_or_else(|| "Downloads".to_string());
|
||||||
|
|
||||||
|
Self {
|
||||||
|
theme: "dark".to_string(),
|
||||||
|
download_dir,
|
||||||
|
video_format: "mp4".to_string(),
|
||||||
|
video_quality: "Best Quality (En İyi)".to_string(),
|
||||||
|
audio_format: "mp3".to_string(),
|
||||||
|
audio_quality: "Best Quality (En İyi)".to_string(),
|
||||||
|
cookies_mode: "none".to_string(),
|
||||||
|
cookies_browser: "chrome".to_string(),
|
||||||
|
cookies_path: String::new(),
|
||||||
|
embed_subtitles: false,
|
||||||
|
subtitle_lang: "tr,en".to_string(),
|
||||||
|
embed_thumbnail: true,
|
||||||
|
add_metadata: true,
|
||||||
|
concurrent_fragments: 4,
|
||||||
|
speed_limit: String::new(),
|
||||||
|
proxy: String::new(),
|
||||||
|
ignore_errors: true,
|
||||||
|
sponsorblock_remove: false,
|
||||||
|
sponsorblock_cats: "sponsor,intro,outro,selfpromo,interaction".to_string(),
|
||||||
|
auto_update_on_startup: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_default_config() {
|
||||||
|
let cfg = AppConfig::default();
|
||||||
|
assert_eq!(cfg.theme, "dark");
|
||||||
|
assert_eq!(cfg.video_format, "mp4");
|
||||||
|
assert_eq!(cfg.audio_format, "mp3");
|
||||||
|
assert_eq!(cfg.concurrent_fragments, 4);
|
||||||
|
assert!(cfg.embed_thumbnail);
|
||||||
|
assert!(cfg.add_metadata);
|
||||||
|
assert!(cfg.auto_update_on_startup);
|
||||||
|
assert!(!cfg.download_dir.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_config_json_roundtrip() {
|
||||||
|
let cfg = AppConfig::default();
|
||||||
|
let json = serde_json::to_string(&cfg).expect("Serialization failed");
|
||||||
|
let deserialized: AppConfig = serde_json::from_str(&json).expect("Deserialization failed");
|
||||||
|
assert_eq!(cfg.theme, deserialized.theme);
|
||||||
|
assert_eq!(cfg.concurrent_fragments, deserialized.concurrent_fragments);
|
||||||
|
}
|
||||||
|
}
|
||||||
12
src-tauri/src/models/dependencies.rs
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct DependencyStatus {
|
||||||
|
pub ytdlp_installed: bool,
|
||||||
|
pub ytdlp_version: Option<String>,
|
||||||
|
pub ffmpeg_installed: bool,
|
||||||
|
pub ffmpeg_version: Option<String>,
|
||||||
|
pub deno_installed: bool,
|
||||||
|
pub deno_version: Option<String>,
|
||||||
|
pub bin_dir: String,
|
||||||
|
}
|
||||||
38
src-tauri/src/models/download.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct DownloadRequest {
|
||||||
|
pub id: String,
|
||||||
|
pub url: String,
|
||||||
|
pub media_type: String, // "video" | "audio"
|
||||||
|
pub format: String,
|
||||||
|
pub quality: String,
|
||||||
|
pub download_dir: Option<String>,
|
||||||
|
pub clip_start: Option<String>,
|
||||||
|
pub clip_end: Option<String>,
|
||||||
|
pub embed_subtitles: Option<bool>,
|
||||||
|
pub embed_thumbnail: Option<bool>,
|
||||||
|
pub concurrent_fragments: Option<u32>,
|
||||||
|
pub sponsorblock: Option<bool>,
|
||||||
|
pub playlist_start: Option<u32>,
|
||||||
|
pub playlist_end: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct DownloadProgress {
|
||||||
|
pub id: String,
|
||||||
|
pub percent: f32,
|
||||||
|
pub speed: String,
|
||||||
|
pub downloaded_bytes: String,
|
||||||
|
pub total_bytes: String,
|
||||||
|
pub eta: String,
|
||||||
|
pub status: String, // "downloading" | "processing" | "completed" | "error" | "cancelled" | "live_recording"
|
||||||
|
pub message: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct LogMessage {
|
||||||
|
pub id: String,
|
||||||
|
pub level: String, // "info" | "success" | "warn" | "error" | "accent"
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
38
src-tauri/src/models/history.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct HistoryItem {
|
||||||
|
pub id: String,
|
||||||
|
pub date: String,
|
||||||
|
pub title: String,
|
||||||
|
pub url: String,
|
||||||
|
pub format: String,
|
||||||
|
pub size: String,
|
||||||
|
pub file_path: String,
|
||||||
|
pub status: String, // "completed" | "error"
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_history_item_serialization() {
|
||||||
|
let item = HistoryItem {
|
||||||
|
id: "dl-12345".to_string(),
|
||||||
|
date: "11.11.2026 23:45".to_string(),
|
||||||
|
title: "Test Video".to_string(),
|
||||||
|
url: "https://youtube.com/watch?v=123".to_string(),
|
||||||
|
format: "mp4".to_string(),
|
||||||
|
size: "15.4 MB".to_string(),
|
||||||
|
file_path: "C:\\Downloads\\Test Video.mp4".to_string(),
|
||||||
|
status: "completed".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let json = serde_json::to_string(&item).expect("Serialize item");
|
||||||
|
let decoded: HistoryItem = serde_json::from_str(&json).expect("Deserialize item");
|
||||||
|
assert_eq!(item.id, decoded.id);
|
||||||
|
assert_eq!(item.title, decoded.title);
|
||||||
|
assert_eq!(item.status, decoded.status);
|
||||||
|
}
|
||||||
|
}
|
||||||
42
src-tauri/src/models/kick.rs
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct KickChannelInfo {
|
||||||
|
pub channel_name: String,
|
||||||
|
pub is_live: bool,
|
||||||
|
pub stream_title: Option<String>,
|
||||||
|
pub viewer_count: Option<u64>,
|
||||||
|
pub category: Option<String>,
|
||||||
|
pub playback_url: Option<String>,
|
||||||
|
pub avatar_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct KickVod {
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
pub duration: String,
|
||||||
|
pub views: u64,
|
||||||
|
pub date: String,
|
||||||
|
pub url: String,
|
||||||
|
pub thumbnail: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct KickClip {
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
pub duration: String,
|
||||||
|
pub views: u64,
|
||||||
|
pub date: String,
|
||||||
|
pub url: String,
|
||||||
|
pub thumbnail: Option<String>,
|
||||||
|
pub creator: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct KickDiscoveryResponse {
|
||||||
|
pub channel: Option<KickChannelInfo>,
|
||||||
|
pub vods: Vec<KickVod>,
|
||||||
|
pub clips: Vec<KickClip>,
|
||||||
|
}
|
||||||
14
src-tauri/src/models/metadata.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct MediaMetadata {
|
||||||
|
pub url: String,
|
||||||
|
pub title: String,
|
||||||
|
pub uploader: String,
|
||||||
|
pub duration: String,
|
||||||
|
pub duration_seconds: Option<f64>,
|
||||||
|
pub thumbnail: String,
|
||||||
|
pub resolutions: Vec<String>,
|
||||||
|
pub is_playlist: bool,
|
||||||
|
pub playlist_count: Option<usize>,
|
||||||
|
}
|
||||||
13
src-tauri/src/models/mod.rs
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
pub mod config;
|
||||||
|
pub mod dependencies;
|
||||||
|
pub mod download;
|
||||||
|
pub mod history;
|
||||||
|
pub mod kick;
|
||||||
|
pub mod metadata;
|
||||||
|
|
||||||
|
pub use config::AppConfig;
|
||||||
|
pub use dependencies::DependencyStatus;
|
||||||
|
pub use download::{DownloadProgress, DownloadRequest, LogMessage};
|
||||||
|
pub use history::HistoryItem;
|
||||||
|
pub use kick::{KickChannelInfo, KickClip, KickDiscoveryResponse, KickVod};
|
||||||
|
pub use metadata::MediaMetadata;
|
||||||
48
src-tauri/src/services/config_service.rs
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
use std::fs;
|
||||||
|
use crate::error::AppError;
|
||||||
|
use crate::models::AppConfig;
|
||||||
|
use crate::services::paths::{ensure_dirs, get_config_path};
|
||||||
|
|
||||||
|
pub fn load_config() -> Result<AppConfig, AppError> {
|
||||||
|
ensure_dirs()?;
|
||||||
|
let path = get_config_path()?;
|
||||||
|
|
||||||
|
if !path.exists() {
|
||||||
|
let default_config = AppConfig::default();
|
||||||
|
save_config(&default_config)?;
|
||||||
|
return Ok(default_config);
|
||||||
|
}
|
||||||
|
|
||||||
|
let content = fs::read_to_string(&path)?;
|
||||||
|
match serde_json::from_str::<AppConfig>(&content) {
|
||||||
|
Ok(cfg) => Ok(cfg),
|
||||||
|
Err(e) => {
|
||||||
|
crate::services::logger_service::log(
|
||||||
|
"warn",
|
||||||
|
"CONFIG",
|
||||||
|
&format!("Bozuk config.json tespit edildi ({}), yedekleniyor...", e),
|
||||||
|
);
|
||||||
|
// Self-healing: Backup corrupted file to avoid permanent loss
|
||||||
|
let backup_name = format!(
|
||||||
|
"config.corrupt-{}.json",
|
||||||
|
chrono::Local::now().format("%Y%m%d-%H%M%S")
|
||||||
|
);
|
||||||
|
let backup_path = path.with_file_name(backup_name);
|
||||||
|
let _ = fs::copy(&path, &backup_path);
|
||||||
|
|
||||||
|
let default_config = AppConfig::default();
|
||||||
|
let _ = save_config(&default_config);
|
||||||
|
Ok(default_config)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_config(config: &AppConfig) -> Result<(), AppError> {
|
||||||
|
ensure_dirs()?;
|
||||||
|
let path = get_config_path()?;
|
||||||
|
let tmp_path = path.with_extension("tmp");
|
||||||
|
let serialized = serde_json::to_string_pretty(config)?;
|
||||||
|
fs::write(&tmp_path, serialized)?;
|
||||||
|
fs::rename(&tmp_path, &path)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
195
src-tauri/src/services/dependency_service.rs
Normal file
|
|
@ -0,0 +1,195 @@
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::{copy, Cursor};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::Command;
|
||||||
|
use crate::error::AppError;
|
||||||
|
use crate::models::DependencyStatus;
|
||||||
|
use crate::services::paths::{ensure_dirs, get_bin_dir, resolve_binary_path};
|
||||||
|
|
||||||
|
pub async fn check_dependencies() -> DependencyStatus {
|
||||||
|
let _ = ensure_dirs();
|
||||||
|
let bin_dir = get_bin_dir()
|
||||||
|
.map(|p| p.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let (ytdlp_installed, ytdlp_version) = check_binary("yt-dlp");
|
||||||
|
let (ffmpeg_installed, ffmpeg_version) = check_binary("ffmpeg");
|
||||||
|
let (deno_installed, deno_version) = check_binary("deno");
|
||||||
|
|
||||||
|
DependencyStatus {
|
||||||
|
ytdlp_installed,
|
||||||
|
ytdlp_version,
|
||||||
|
ffmpeg_installed,
|
||||||
|
ffmpeg_version,
|
||||||
|
deno_installed,
|
||||||
|
deno_version,
|
||||||
|
bin_dir,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_binary(name: &str) -> (bool, Option<String>) {
|
||||||
|
let bin_path = resolve_binary_path(name);
|
||||||
|
let mut cmd = Command::new(&bin_path);
|
||||||
|
cmd.arg("--version");
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||||
|
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
match cmd.output() {
|
||||||
|
Ok(output) if output.status.success() => {
|
||||||
|
let ver = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||||
|
let first_line = ver.lines().next().unwrap_or(&ver).to_string();
|
||||||
|
(true, Some(first_line))
|
||||||
|
}
|
||||||
|
_ => (false, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn install_ytdlp<F>(progress_cb: F) -> Result<String, AppError>
|
||||||
|
where
|
||||||
|
F: Fn(f32, &str) + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
ensure_dirs()?;
|
||||||
|
let bin_dir = get_bin_dir()?;
|
||||||
|
let target_file = bin_dir.join(if cfg!(windows) { "yt-dlp.exe" } else { "yt-dlp" });
|
||||||
|
|
||||||
|
progress_cb(10.0, "yt-dlp indiriliyor...");
|
||||||
|
let url = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe";
|
||||||
|
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent("LDownloader/3.6.0")
|
||||||
|
.build()?;
|
||||||
|
|
||||||
|
let response = client.get(url).send().await?;
|
||||||
|
if !response.status().is_success() {
|
||||||
|
return Err(AppError::Network(format!(
|
||||||
|
"yt-dlp indirme isteği başarısız oldu: HTTP {}",
|
||||||
|
response.status()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let bytes = response.bytes().await?;
|
||||||
|
progress_cb(80.0, "Dosya diske kaydediliyor...");
|
||||||
|
std::fs::write(&target_file, bytes)?;
|
||||||
|
|
||||||
|
progress_cb(100.0, "Kurulum tamamlandı!");
|
||||||
|
let (_, version) = check_binary("yt-dlp");
|
||||||
|
Ok(version.unwrap_or_else(|| "Bilinmeyen Sürüm".to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn install_ffmpeg<F>(progress_cb: F) -> Result<String, AppError>
|
||||||
|
where
|
||||||
|
F: Fn(f32, &str) + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
ensure_dirs()?;
|
||||||
|
let bin_dir = get_bin_dir()?;
|
||||||
|
|
||||||
|
progress_cb(10.0, "FFmpeg arşivi indiriliyor...");
|
||||||
|
// Fast GitHub mirror of ffmpeg essentials release
|
||||||
|
let url = "https://github.com/GyanD/codexffmpeg/releases/download/7.1/ffmpeg-7.1-essentials_build.zip";
|
||||||
|
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent("LDownloader/3.6.0")
|
||||||
|
.build()?;
|
||||||
|
|
||||||
|
let response = client.get(url).send().await?;
|
||||||
|
if !response.status().is_success() {
|
||||||
|
return Err(AppError::Network(format!(
|
||||||
|
"FFmpeg indirme isteği başarısız oldu: HTTP {}",
|
||||||
|
response.status()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let bytes = response.bytes().await?;
|
||||||
|
progress_cb(70.0, "FFmpeg ikilileri arşivden çıkarılıyor...");
|
||||||
|
|
||||||
|
let bin_dir_clone = bin_dir.clone();
|
||||||
|
tokio::task::spawn_blocking(move || -> Result<(), AppError> {
|
||||||
|
let cursor = Cursor::new(bytes);
|
||||||
|
let mut archive = zip::ZipArchive::new(cursor)
|
||||||
|
.map_err(|e| AppError::Internal(format!("Zip açma hatası: {}", e)))?;
|
||||||
|
|
||||||
|
for i in 0..archive.len() {
|
||||||
|
let mut file = archive
|
||||||
|
.by_index(i)
|
||||||
|
.map_err(|e| AppError::Internal(format!("Zip öğesi okunamadı: {}", e)))?;
|
||||||
|
let name = file.name().to_string();
|
||||||
|
|
||||||
|
if name.ends_with("ffmpeg.exe") || name.ends_with("ffprobe.exe") {
|
||||||
|
let file_name = PathBuf::from(&name)
|
||||||
|
.file_name()
|
||||||
|
.map(|f| f.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_else(|| "ffmpeg.exe".to_string());
|
||||||
|
|
||||||
|
let outpath = bin_dir_clone.join(file_name);
|
||||||
|
let mut outfile = File::create(&outpath)?;
|
||||||
|
copy(&mut file, &mut outfile)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| AppError::Internal(format!("Tokio worker hatası: {}", e)))??;
|
||||||
|
|
||||||
|
progress_cb(100.0, "FFmpeg hazır!");
|
||||||
|
let (_, version) = check_binary("ffmpeg");
|
||||||
|
Ok(version.unwrap_or_else(|| "7.1".to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn install_deno<F>(progress_cb: F) -> Result<String, AppError>
|
||||||
|
where
|
||||||
|
F: Fn(f32, &str) + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
ensure_dirs()?;
|
||||||
|
let bin_dir = get_bin_dir()?;
|
||||||
|
|
||||||
|
progress_cb(10.0, "Deno JS motoru indiriliyor...");
|
||||||
|
let url = "https://github.com/denoland/deno/releases/latest/download/deno-x86_64-pc-windows-msvc.zip";
|
||||||
|
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent("LDownloader/3.6.0")
|
||||||
|
.build()?;
|
||||||
|
|
||||||
|
let response = client.get(url).send().await?;
|
||||||
|
if !response.status().is_success() {
|
||||||
|
return Err(AppError::Network(format!(
|
||||||
|
"Deno indirme isteği başarısız oldu: HTTP {}",
|
||||||
|
response.status()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let bytes = response.bytes().await?;
|
||||||
|
progress_cb(70.0, "Deno arşivden çıkarılıyor...");
|
||||||
|
|
||||||
|
let bin_dir_clone = bin_dir.clone();
|
||||||
|
tokio::task::spawn_blocking(move || -> Result<(), AppError> {
|
||||||
|
let cursor = Cursor::new(bytes);
|
||||||
|
let mut archive = zip::ZipArchive::new(cursor)
|
||||||
|
.map_err(|e| AppError::Internal(format!("Deno Zip açma hatası: {}", e)))?;
|
||||||
|
|
||||||
|
for i in 0..archive.len() {
|
||||||
|
let mut file = archive
|
||||||
|
.by_index(i)
|
||||||
|
.map_err(|e| AppError::Internal(format!("Zip öğesi okunamadı: {}", e)))?;
|
||||||
|
let name = file.name().to_string();
|
||||||
|
|
||||||
|
if name.ends_with("deno.exe") {
|
||||||
|
let outpath = bin_dir_clone.join("deno.exe");
|
||||||
|
let mut outfile = File::create(&outpath)?;
|
||||||
|
copy(&mut file, &mut outfile)?;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| AppError::Internal(format!("Tokio worker hatası: {}", e)))??;
|
||||||
|
|
||||||
|
progress_cb(100.0, "Deno JS motoru hazır!");
|
||||||
|
let (_, version) = check_binary("deno");
|
||||||
|
Ok(version.unwrap_or_else(|| "Deno".to_string()))
|
||||||
|
}
|
||||||