dj-cli 0.1.0

A CLI tool for DJs to download MP3s from YouTube
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use color_eyre::Result;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use ratatui::{DefaultTerminal, Frame};
// Removed ratatui_input for simplicity
use std::path::PathBuf;
use std::time::{Duration, UNIX_EPOCH};
use std::{fs, process::Stdio};
use tracing::{info, warn, error};
use regex::Regex;

// Maximum input length to prevent memory issues and UI corruption
const MAX_INPUT_LENGTH: usize = 500;
const MAX_PASTE_LENGTH: usize = 10000;

/// Application state
#[derive(Debug)]
pub struct App {
    /// Should the application exit?
    pub running: bool,
    /// YouTube URL input
    pub input: String,
    /// Current status message
    pub status_message: String,
    /// Download status
    pub download_status: DownloadStatus,
    /// Focus state (Input or Convert button)
    pub focus: Focus,
    /// Batch mode enabled
    pub batch_mode: bool,
    /// List of URLs for batch download
    pub batch_urls: Vec<String>,
    /// Current batch download progress
    pub batch_progress: BatchProgress,
    /// Should clear the frame on next draw
    pub should_clear: bool,
    /// Download history for display
    pub download_history: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct BatchProgress {
    pub current: usize,
    pub total: usize,
    pub completed: Vec<String>,
    pub failed: Vec<String>,
}

#[derive(Debug, Clone)]
pub enum DownloadStatus {
    Idle,
    Downloading,
    Success(String),
    Error(String),
}

#[derive(Debug, Clone, PartialEq)]
pub enum Focus {
    Input,
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

impl App {
    pub fn new() -> Self {
        Self {
            running: true,
            input: String::new(),
            status_message: "Paste a YouTube URL and press Enter to download MP3".to_string(),
            download_status: DownloadStatus::Idle,
            focus: Focus::Input,
            batch_mode: false,
            batch_urls: Vec::new(),
            batch_progress: BatchProgress {
                current: 0,
                total: 0,
                completed: Vec::new(),
                failed: Vec::new(),
            },
            should_clear: false,
            download_history: Vec::new(),
        }
    }

    /// Main application loop
    pub async fn run(mut self, mut terminal: DefaultTerminal) -> Result<()> {
        info!("Starting main app loop");
        
        while self.running {
            // Only clear the terminal if needed (best practice)
            if self.should_clear {
                terminal.clear()?;
                self.should_clear = false;
            }
            // Draw UI
            terminal.draw(|frame| self.draw(frame))?;
            // Handle events
            if event::poll(Duration::from_millis(100))? {
                if let Event::Key(key) = event::read()? {
                    self.handle_key_event(key).await?;
                }
            }
        }
        
        info!("App loop finished");
        Ok(())
    }

    /// Draw the application UI
    fn draw(&mut self, frame: &mut Frame) {
        crate::ui::render(frame, self);
    }

    /// Sanitize and validate input text
    fn sanitize_input(&mut self, input: &str) -> String {
        // First, truncate if too long
        let truncated = if input.len() > MAX_PASTE_LENGTH {
            warn!("Input truncated from {} to {} characters", input.len(), MAX_PASTE_LENGTH);
            &input[..MAX_PASTE_LENGTH]
        } else {
            input
        };

        // Try to extract YouTube URL from the text
        if let Some(url) = self.extract_youtube_url(truncated) {
            info!("Extracted YouTube URL: {}", url);
            return url;
        }

        // If no URL found, clean the text and apply length limit
        let cleaned = self.clean_text(truncated);
        if cleaned.len() > MAX_INPUT_LENGTH {
            warn!("Cleaned input truncated from {} to {} characters", cleaned.len(), MAX_INPUT_LENGTH);
            cleaned[..MAX_INPUT_LENGTH].to_string()
        } else {
            cleaned
        }
    }

    /// Extract YouTube URL from messy text
    fn extract_youtube_url(&self, text: &str) -> Option<String> {
        // YouTube URL patterns (in order of preference)
        let patterns = [
            // Full URLs with https
            r"https://(?:www\.)?youtube\.com/watch\?v=([a-zA-Z0-9_-]+)(?:[&\w=]*)?",
            r"https://youtu\.be/([a-zA-Z0-9_-]+)(?:\?[&\w=]*)?",
            // URLs without https
            r"(?:www\.)?youtube\.com/watch\?v=([a-zA-Z0-9_-]+)(?:[&\w=]*)?",
            r"youtu\.be/([a-zA-Z0-9_-]+)(?:\?[&\w=]*)?",
            // Just the watch part
            r"watch\?v=([a-zA-Z0-9_-]+)(?:[&\w=]*)?",
        ];

        for pattern in &patterns {
            if let Ok(regex) = Regex::new(pattern) {
                if let Some(captures) = regex.captures(text) {
                    if let Some(video_id) = captures.get(1) {
                        let url = format!("https://www.youtube.com/watch?v={}", video_id.as_str());
                        info!("Extracted YouTube URL from pattern '{}': {}", pattern, url);
                        return Some(url);
                    }
                }
            }
        }

        None
    }

    /// Clean text by removing control characters and normalizing whitespace
    fn clean_text(&self, text: &str) -> String {
        text.chars()
            .filter(|c| {
                // Keep printable ASCII, basic Unicode, and essential whitespace
                c.is_ascii_graphic() || c.is_ascii_whitespace() || (*c as u32) > 127
            })
            .collect::<String>()
            .split_whitespace()  // Normalize whitespace
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// Handle character input with proper sanitization
    fn handle_char_input(&mut self, c: char) {
        // Check if adding this character would exceed the limit
        if self.input.len() >= MAX_INPUT_LENGTH {
            warn!("Input at maximum length ({}), ignoring character", MAX_INPUT_LENGTH);
            self.status_message = format!("Input limit reached ({} characters)", MAX_INPUT_LENGTH);
            return;
        }

        // Filter out problematic characters
        if c.is_control() && c != '\t' {
            warn!("Ignoring control character: {:?}", c);
            return;
        }

        self.input.push(c);
        
        // Clear any previous status messages when user types normally
        if self.status_message.starts_with("Input limit reached") || 
           self.status_message.starts_with("Large input sanitized") {
            self.status_message.clear();
        }
    }

    /// Handle paste operation with sanitization
    fn handle_paste(&mut self, pasted_text: &str) {
        let original_len = pasted_text.len();
        let sanitized = self.sanitize_input(pasted_text);
        
        if sanitized != pasted_text {
            if original_len > MAX_PASTE_LENGTH {
                self.status_message = format!(
                    "Large input sanitized: {}{} chars (extracted URL or cleaned text)", 
                    original_len, sanitized.len()
                );
            } else {
                self.status_message = "Input cleaned and URL extracted".to_string();
            }
            info!("Input sanitized: original {} chars → {} chars", original_len, sanitized.len());
        }

        // Replace the current input with sanitized content
        self.input = sanitized;
    }

    /// Handle keyboard events with improved error handling and input sanitization
    async fn handle_key_event(&mut self, key: KeyEvent) -> Result<()> {
        // Global quit command
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            info!("User quit with Ctrl+C");
            self.running = false;
            return Ok(());
        }

        // Use a separate method for handling that can't crash the UI
        if let Err(e) = self.handle_key_event_safe(key).await {
            error!("Error handling key event: {}", e);
            self.status_message = format!("Error: {}", e);
            // Don't crash the UI - just show the error message
        }

        Ok(())
    }

    /// Safe key event handling that catches errors
    async fn handle_key_event_safe(&mut self, key: KeyEvent) -> Result<()> {
        match key.code {
            KeyCode::Esc => {
                self.running = false;
            }
            KeyCode::Enter => {
                if !self.input.trim().is_empty() {
                    if self.batch_mode {
                        self.batch_urls.push(self.input.clone());
                        self.status_message = format!("Added URL {} to batch (total: {})", 
                            self.batch_urls.len(), self.batch_urls.len());
                        self.input.clear();
                    } else {
                        self.start_download(128).await?;
                    }
                }
            }
            KeyCode::Backspace => {
                self.input.pop();
            }
            KeyCode::Delete => {
                self.input.clear();
            }
            KeyCode::Tab => {
                // Tab does nothing now since we only have input focus
                // Keeping this for compatibility but it doesn't change focus
            }
            KeyCode::F(5) => {
                // F5 to clear input and extract URL from current content
                if !self.input.is_empty() {
                    let original = self.input.clone();
                    self.handle_paste(&original);
                }
            }
            KeyCode::Char(c @ ('b' | 'B')) => {
                if key.modifiers.contains(KeyModifiers::CONTROL) {
                    // Toggle batch mode with Ctrl+B
                    self.batch_mode = !self.batch_mode;
                    self.should_clear = true;
                    if self.batch_mode {
                        self.status_message = "🎯 Batch mode ON - Add URLs with Enter, download with Ctrl+D".to_string();
                        self.batch_urls.clear();
                        self.batch_progress = BatchProgress {
                            current: 0,
                            total: 0,
                            completed: Vec::new(),
                            failed: Vec::new(),
                        };
                    } else {
                        self.status_message = "Single URL mode - Paste a YouTube URL and press Enter to download".to_string();
                        self.batch_progress = BatchProgress {
                            current: 0,
                            total: 0,
                            completed: Vec::new(),
                            failed: Vec::new(),
                        };
                    }
                } else {
                    // Handle regular 'b' character input
                    self.handle_char_input(c);
                }
            }
            KeyCode::Char(c @ ('d' | 'D')) => {
                if key.modifiers.contains(KeyModifiers::CONTROL) && self.batch_mode {
                    // Start batch download with Ctrl+D
                    self.start_batch_download(128).await?;
                } else {
                    // Handle regular 'd' character input
                    self.handle_char_input(c);
                }
            }
            KeyCode::Char('1') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                if !self.input.trim().is_empty() {
                    self.start_download(128).await?;
                }
            }
            KeyCode::Char('2') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                if !self.input.trim().is_empty() {
                    self.start_download(256).await?;
                }
            }
            KeyCode::Char('v') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                // Handle Ctrl+V paste - for now just inform user about F5
                self.status_message = "💡 Paste detected! Press F5 to clean and extract URL from pasted content".to_string();
                info!("Ctrl+V detected - user should use F5 for URL extraction");
            }
            KeyCode::Char('a') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                // Handle Ctrl+A - select all (just clear input for simplicity)
                info!("Ctrl+A detected - clearing input");
            }
            KeyCode::Char(c) => {
                // Handle other character input
                self.handle_char_input(c);
            }
            _ => {}
        }

        Ok(())
    }

    /// Start downloading the YouTube video as MP3 with robust error handling
    async fn start_download(&mut self, bitrate: u32) -> Result<()> {
        let url = self.input.trim();
        
        if url.is_empty() {
            self.status_message = "Please enter a YouTube URL".to_string();
            warn!("Empty URL provided");
            return Ok(());
        }

        if !url.contains("youtube.com") && !url.contains("youtu.be") {
            self.status_message = "Please enter a valid YouTube URL".to_string();
            warn!("Invalid URL provided: {}", url);
            return Ok(());
        }

        // Wrap download in error handling to prevent crashes
        if let Err(e) = self.perform_download(url.to_string(), bitrate).await {
            error!("Download failed: {}", e);
            self.download_status = DownloadStatus::Error(e.to_string());
            self.status_message = format!("❌ Download failed: {}", e);
        }
        
        Ok(())
    }

    /// Perform the actual download with proper error isolation
    async fn perform_download(&mut self, url: String, bitrate: u32) -> Result<()> {

        // Starting download silently  
        self.download_status = DownloadStatus::Downloading;
        self.status_message = format!("🎵 Downloading MP3 at {}kbps... Please wait", bitrate);
        
        // Clear the input field when download starts
        self.input.clear();

        // Download directly to Downloads folder (no subfolder)
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
        let output_dir = PathBuf::from(home).join("Downloads");

        // Download using yt-dlp - clean and simple
        let file_path = self.download_mp3(url, output_dir, bitrate).await
            .map_err(|e| color_eyre::eyre::eyre!("Download failed: {}", e))?;
        // Download completed successfully
        self.download_status = DownloadStatus::Success(file_path.clone());
        self.status_message = format!("✅ Successfully downloaded: {}", file_path);
        
        // Add to download history for display - extract just the filename
        if let Some(filename) = file_path.strip_prefix("✅ Downloaded: ") {
            self.download_history.push(filename.to_string());
        } else {
            // Fallback in case format changes
            self.download_history.push(file_path.clone());
        }

        Ok(())
    }

    /// Start batch downloading multiple YouTube videos as MP3
    async fn start_batch_download(&mut self, bitrate: u32) -> Result<()> {
        if self.batch_urls.is_empty() {
            self.status_message = "❌ No URLs in batch. Add URLs with Enter first.".to_string();
            return Ok(());
        }

        info!("Starting batch download for {} URLs at {}kbps", self.batch_urls.len(), bitrate);
        self.download_status = DownloadStatus::Downloading;
        self.batch_progress = BatchProgress {
            current: 0,
            total: self.batch_urls.len(),
            completed: Vec::new(),
            failed: Vec::new(),
        };

        // Download directly to Downloads folder (no subfolder)  
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
        let output_dir = PathBuf::from(home).join("Downloads");

        // Download each URL in the batch
        for (index, url) in self.batch_urls.iter().enumerate() {
            self.batch_progress.current = index + 1;
            self.status_message = format!("📥 Downloading {}/{}: {}", index + 1, self.batch_urls.len(), url);

            match self.download_mp3(url.clone(), output_dir.clone(), bitrate).await {
                Ok(file_path) => {
                    // Batch download completed successfully
                    self.batch_progress.completed.push(url.clone());
                    // Add to download history for display - extract just the filename
                    if let Some(filename) = file_path.strip_prefix("✅ Downloaded: ") {
                        self.download_history.push(filename.to_string());
                    } else {
                        // Fallback in case format changes
                        self.download_history.push(file_path);
                    }
                }
                Err(e) => {
                    error!("Download failed for {}: {}", url, e);
                    self.batch_progress.failed.push(url.clone());
                }
            }
        }

        // Final status message
        let success_count = self.batch_progress.completed.len();
        let failed_count = self.batch_progress.failed.len();
        
        if failed_count == 0 {
            self.status_message = format!("✅ Batch complete! All {} downloads successful", success_count);
            self.download_status = DownloadStatus::Success(format!("{} files downloaded", success_count));
        } else {
            self.status_message = format!("⚠️ Batch complete: {} successful, {} failed", success_count, failed_count);
            self.download_status = DownloadStatus::Success(format!("{} successful, {} failed", success_count, failed_count));
        }

        Ok(())
    }

    /// Download MP3 using yt-dlp - clean and simple (2025 best practice)
    async fn download_mp3(
        &self,
        url: String,
        output_dir: PathBuf,
        bitrate: u32,
    ) -> Result<String, Box<dyn std::error::Error>> {
        // Step 1: Get list of existing MP3 files BEFORE download
        let existing_mp3s = self.get_mp3_files(&output_dir).await.unwrap_or_default();

        // Step 2: Do the actual download (back to working logic)
        let output_template = output_dir.join("%(title)s.%(ext)s");
        
        let mut cmd = tokio::process::Command::new("yt-dlp");
        cmd.args(&[
            "--format", "bestaudio",                        // Download ONLY audio stream (no video)
            "--extract-audio",                              // Extract to final format
            "--audio-format", "mp3",                        // Convert to MP3
            "--audio-quality", &format!("{}K", bitrate),    // Bitrate (128K/256K)
            "--output", &output_template.to_string_lossy(), // Save to Downloads/[title].mp3
            "--no-playlist",                                // Single video only
            "--prefer-ffmpeg",                             // Use ffmpeg for conversion
            "--embed-thumbnail",                           // Add album art
            "--add-metadata",                              // Add metadata
            "--no-warnings",                               // Suppress warnings
            "--quiet",                                     // Minimal output
            &url                                           // YouTube URL
        ]);

        // Completely suppress all output to keep TUI clean
        cmd.stdout(Stdio::null())
           .stderr(Stdio::null())
           .stdin(Stdio::null());
        
        let output = cmd.output().await
            .map_err(|_| format!("yt-dlp not found. Please install: brew install yt-dlp"))?;

        if !output.status.success() {
            return Err("Download failed. Check if the YouTube URL is valid and accessible.".into());
        }

        // Give the file system a moment to update
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        // Step 3: Get list of MP3 files AFTER download
        let new_mp3s = self.get_mp3_files(&output_dir).await.unwrap_or_default();

        // Step 4: Find the NEW file (difference between before and after)
        let new_file = new_mp3s.iter()
            .find(|file| !existing_mp3s.contains(file))
            .cloned()
            .unwrap_or_else(|| {
                // If no new file found, try to get the most recently modified MP3
                fs::read_dir(&output_dir)
                    .ok()
                    .and_then(|entries| {
                        entries
                            .filter_map(|e| e.ok())
                            .filter(|e| e.path().extension().map_or(false, |ext| ext == "mp3"))
                            .max_by_key(|e| e.metadata().and_then(|m| m.modified()).unwrap_or(UNIX_EPOCH))
                            .and_then(|e| e.file_name().to_str().map(|s| s.to_string()))
                    })
                    .unwrap_or_else(|| "Unknown.mp3".to_string())
            });

        Ok(format!("✅ Downloaded: {}", new_file))
    }

    /// Helper function to get all MP3 filenames in a directory
    async fn get_mp3_files(&self, dir: &PathBuf) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let mut mp3_files = Vec::new();
        
        // Check if directory exists
        if !dir.exists() {
            return Ok(mp3_files);
        }
        
        let mut entries = tokio::fs::read_dir(dir).await?;
        
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            
            // Only process files (not directories)
            if path.is_file() {
                if let Some(extension) = path.extension() {
                    if extension == "mp3" {
                        if let Some(filename) = path.file_name() {
                            if let Some(filename_str) = filename.to_str() {
                                // Only add non-empty filenames that actually contain text
                                if !filename_str.is_empty() && filename_str.len() > 4 {
                                    mp3_files.push(filename_str.to_string());
                                }
                            }
                        }
                    }
                }
            }
        }
        
        Ok(mp3_files)
    }

    /// Get the current input value
    pub fn input_value(&self) -> &str {
        &self.input
    }

    /// Check if input field is focused
    pub fn is_input_focused(&self) -> bool {
        true // Always focused now since it's the only element
    }

}