feat(downloader): add router query downloader

pull/3834/head
banbxio 2025-03-26 23:20:44 +08:00
parent 68b11395a2
commit 44b89b9b1e
2 changed files with 34 additions and 1 deletions

View File

@ -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 {

View File

@ -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
}