From 44b89b9b1e52cf1c540c85693316d899a8960747 Mon Sep 17 00:00:00 2001 From: banbxio Date: Wed, 26 Mar 2025 23:20:44 +0800 Subject: [PATCH] feat(downloader): add router query downloader --- http/downloader.go | 34 +++++++++++++++++++++++++++++++++- http/http.go | 1 + 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/http/downloader.go b/http/downloader.go index 7fe4513e..6e39ea5f 100644 --- a/http/downloader.go +++ b/http/downloader.go @@ -8,6 +8,7 @@ import ( "github.com/patrickmn/go-cache" "github.com/spf13/afero" "io" + "math" "net/http" "os" "path" @@ -51,7 +52,9 @@ func (wc *WriteCounter) Write(p []byte) (int, error) { n := len(p) wc.task.savedSize += int64(n) wc.task.cache.Set(wc.task.TaskID.String(), wc.task, cache.NoExpiration) - fmt.Printf("Downloaded %d of %d bytes, percent: %.2f%%\n", wc.task.savedSize, wc.task.totalSize, wc.task.Progress()) + if n == 0 { + wc.task.cache.Delete(wc.task.TaskID.String()) + } return n, nil } @@ -84,6 +87,35 @@ func downloadHandler(downloaderCache *cache.Cache) handleFunc { }) } +func downloadStatusHandler(downloaderCache *cache.Cache) handleFunc { + return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) { + if !d.user.Perm.Create || !d.Check(r.URL.Path) { + return http.StatusForbidden, nil + } + taskID := r.URL.Path + taskCacheRaw, ok := downloaderCache.Get(taskID) + if !ok { + return http.StatusNotFound, nil + } + taskCache := taskCacheRaw.(*DownloadTask) + responseBody := map[string]interface{}{ + "progress": math.Round(taskCache.Progress()*1000) / 1000, + "totalSize": taskCache.totalSize, + "savedSize": taskCache.savedSize, + "filename": taskCache.Filename, + "pathname": taskCache.Pathname, + "url": taskCache.URL, + "taskID": taskCache.TaskID.String(), + } + w.Header().Set("Content-Type", "application/json") + err := json.NewEncoder(w).Encode(&responseBody) + if err != nil { + return http.StatusInternalServerError, err + } + return 0, nil + }) +} + func downloadWithTask(fs afero.Fs, task *DownloadTask) error { err := fs.MkdirAll(task.Pathname, files.PermDir) if err != nil { diff --git a/http/http.go b/http/http.go index 28677173..75f15fb8 100644 --- a/http/http.go +++ b/http/http.go @@ -95,6 +95,7 @@ func NewHandler( public.PathPrefix("/share").Handler(monkey(publicShareHandler, "/api/public/share/")).Methods("GET") api.PathPrefix("/download").Handler(monkey(downloadHandler(downloaderCache), "/api/download/")).Methods("POST") + api.PathPrefix("/download").Handler(monkey(downloadStatusHandler(downloaderCache), "/api/download/")).Methods("GET") return stripPrefix(server.BaseURL, r), nil }