feat(download): Add api for download file by url
parent
35d1c09243
commit
77fd4d1519
|
@ -0,0 +1,6 @@
|
|||
package downloader
|
||||
|
||||
type Downloader interface {
|
||||
Download(url string, filename string, pathname string) error
|
||||
GetRatio() float64
|
||||
}
|
|
@ -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)
|
||||
}
|
|
@ -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
|
||||
})
|
||||
}
|
|
@ -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
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue