diff --git a/downloader/downloader.go b/downloader/downloader.go new file mode 100644 index 00000000..d80955d1 --- /dev/null +++ b/downloader/downloader.go @@ -0,0 +1,6 @@ +package downloader + +type Downloader interface { + Download(url string, filename string, pathname string) error + GetRatio() float64 +} diff --git a/downloader/wget.go b/downloader/wget.go new file mode 100644 index 00000000..3481bad7 --- /dev/null +++ b/downloader/wget.go @@ -0,0 +1,49 @@ +package downloader + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" +) + +type Wget struct { + URL string `json:"url,omitempty"` + Filename string `json:"filename,omitempty"` + Pathname string `json:"pathname,omitempty"` + total int64 + received int64 +} + +func newWget(url string, filename string, pathname string) *Wget { + return &Wget{ + URL: url, + Filename: filename, + Pathname: pathname, + } +} + +func (w *Wget) Download(url string, filename string, pathname string) error { + _, err := os.Stat(pathname) + if err != nil && os.IsNotExist(err) { + err := os.Mkdir(pathname, 0755) + if err != nil { + return err + } + } + download_filepath := filepath.Join(pathname, filename) + _, err = os.Stat(download_filepath) + if err != nil && os.IsExist(err) { + return err + } + output, err := exec.Command("wget", "-O", download_filepath, url).CombinedOutput() + if err != nil { + return err + } + fmt.Printf("%s\n", output) + return nil +} + +func (w *Wget) GetRatio() float64 { + return float64(w.received) / float64(w.total) +} diff --git a/http/downloader.go b/http/downloader.go new file mode 100644 index 00000000..a41dabc6 --- /dev/null +++ b/http/downloader.go @@ -0,0 +1,27 @@ +package http + +import ( + "encoding/json" + "fmt" + "github.com/filebrowser/filebrowser/v2/downloader" + "net/http" +) + +func downloadHandler() handleFunc { + return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) { + fmt.Printf("wget: %v\n", d.user.Perm.Create) + if !d.user.Perm.Create { + return http.StatusForbidden, nil + } + var wget downloader.Wget + if err := json.NewDecoder(r.Body).Decode(&wget); err != nil { + return http.StatusBadRequest, err + } + + err := wget.Download(wget.URL, wget.Filename, wget.Pathname) + if err != nil { + return http.StatusInternalServerError, err + } + return http.StatusNoContent, nil + }) +} diff --git a/http/http.go b/http/http.go index 620c43fd..05a65b28 100644 --- a/http/http.go +++ b/http/http.go @@ -92,5 +92,7 @@ func NewHandler( public.PathPrefix("/dl").Handler(monkey(publicDlHandler, "/api/public/dl/")).Methods("GET") public.PathPrefix("/share").Handler(monkey(publicShareHandler, "/api/public/share/")).Methods("GET") + api.PathPrefix("/download").Handler(monkey(downloadHandler(), "/api/download/")).Methods("POST") + return stripPrefix(server.BaseURL, r), nil }