From 37a36a3e4013a77ebab7f0b3a04a6348bd2e4b06 Mon Sep 17 00:00:00 2001 From: banbxio Date: Wed, 2 Apr 2025 19:19:17 +0800 Subject: [PATCH] feat(downloader): add cancel download handler for task management --- http/downloader.go | 18 ++++++++++++++++++ http/http.go | 1 + 2 files changed, 19 insertions(+) diff --git a/http/downloader.go b/http/downloader.go index ff396efd..b40c9cfb 100644 --- a/http/downloader.go +++ b/http/downloader.go @@ -119,6 +119,24 @@ func downloadStatusHandler(downloaderCache *cache.Cache) handleFunc { }) } +func cancelDownloadHandler(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) + if taskCache.cancel != nil { + taskCache.cancel() + } + return http.StatusOK, nil + }) +} + func downloadWithTask(fs afero.Fs, task *DownloadTask) error { ctx, cancel := context.WithCancel(context.Background()) task.cancel = cancel diff --git a/http/http.go b/http/http.go index 75f15fb8..efa0a1f2 100644 --- a/http/http.go +++ b/http/http.go @@ -96,6 +96,7 @@ func NewHandler( api.PathPrefix("/download").Handler(monkey(downloadHandler(downloaderCache), "/api/download/")).Methods("POST") api.PathPrefix("/download").Handler(monkey(downloadStatusHandler(downloaderCache), "/api/download/")).Methods("GET") + api.PathPrefix("/download").Handler(monkey(cancelDownloadHandler(downloaderCache), "/api/download/")).Methods("DELETE") return stripPrefix(server.BaseURL, r), nil }