From 4a29197b5f0d6805df420a78f85080765b1b7ab8 Mon Sep 17 00:00:00 2001 From: Arya Gorjipour <36107942+Aryagorjipour@users.noreply.github.com> Date: Sat, 23 Nov 2024 08:55:31 +0330 Subject: [PATCH] feat: Add the watch command to return the list of downloads in 1 second intervals with the ability to exit --- internal/manager/manager.go | 40 ++++++++++++++++++++++++++++++++++++- internal/ui/ui.go | 18 ++++++----------- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/internal/manager/manager.go b/internal/manager/manager.go index 2c799c3..1a2b452 100644 --- a/internal/manager/manager.go +++ b/internal/manager/manager.go @@ -1,9 +1,14 @@ package manager import ( + "bufio" "fmt" - "github.com/Aryagorjipour/smart-file-downloader/internal/task" + "os" + "strings" "sync" + "time" + + "github.com/Aryagorjipour/smart-file-downloader/internal/task" ) // DownloadManager manages download tasks @@ -92,3 +97,36 @@ func (dm *DownloadManager) GetTasks() map[int]*task.DownloadTask { } return copyTasks } + +func (mgr *DownloadManager) Watch() { + reader := bufio.NewReader(os.Stdin) + ticker := time.NewTicker(1 * time.Second) + defer ticker.Stop() + + done := make(chan bool) + + go func() { + for { + select { + case <-ticker.C: + mgr.ListDownloads() + case <-done: + return + } + } + }() + + for { + input, err := reader.ReadString('\n') + if err != nil { + fmt.Println("Error reading input:", err) + continue + } + if strings.TrimSpace(input) == "q" { + break + } + } + + done <- true + fmt.Println("Exited watch mode.") +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index d07fb8f..2300be5 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -3,11 +3,11 @@ package ui import ( "bufio" "fmt" - "github.com/Aryagorjipour/smart-file-downloader/internal/manager" "os" "strconv" "strings" - "time" + + "github.com/Aryagorjipour/smart-file-downloader/internal/manager" ) // Start starts the UI @@ -16,15 +16,6 @@ func Start(mgr *manager.DownloadManager) { fmt.Println("Concurrent File Downloader") fmt.Printf("Downloads will be saved to: %s\n", mgr.DownloadDir) - // Start a goroutine to display progress periodically - go func() { - for len(mgr.Tasks) > 0 { - time.Sleep(2 * time.Second) - mgr.ListDownloads() - fmt.Println("------") - } - }() - for { fmt.Println("Commands:") fmt.Println("1. add ") @@ -32,7 +23,8 @@ func Start(mgr *manager.DownloadManager) { fmt.Println("3. pause ") fmt.Println("4. resume ") fmt.Println("5. cancel ") - fmt.Println("6. exit") + fmt.Println("6. watch") + fmt.Println("0. exit") fmt.Print("Enter command: ") input, err := reader.ReadString('\n') if err != nil { @@ -89,6 +81,8 @@ func Start(mgr *manager.DownloadManager) { continue } mgr.CancelDownload(id) + case "watch": + mgr.Watch() case "exit": fmt.Println("Exiting...") os.Exit(0)