75 lines
1.6 KiB
Go
75 lines
1.6 KiB
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"gitnet.fr/deblan/mu-go/fs"
|
|
)
|
|
|
|
type ApiError struct {
|
|
Error string `json:"error"`
|
|
}
|
|
|
|
func List(e echo.Context, directory, url string) error {
|
|
files, err := fs.Files(directory, url)
|
|
if err != nil {
|
|
return e.JSON(http.StatusInternalServerError, ApiError{Error: fmt.Sprintf("%s", err)})
|
|
}
|
|
|
|
name := e.QueryParam("name")
|
|
order := e.QueryParam("order")
|
|
|
|
if name != "" {
|
|
name = strings.ToLower(name)
|
|
var newFiles []fs.File
|
|
|
|
for _, file := range files {
|
|
isMatchingName, _ := regexp.MatchString(name, strings.ToLower(file.Name))
|
|
|
|
if isMatchingName {
|
|
newFiles = append(newFiles, file)
|
|
}
|
|
}
|
|
|
|
files = newFiles
|
|
}
|
|
|
|
sort.SliceStable(files, func(i, j int) bool {
|
|
if order == "date" {
|
|
return files[i].Date < files[j].Date
|
|
} else if order == "name" {
|
|
return files[i].Name < files[j].Name
|
|
}
|
|
|
|
return false
|
|
})
|
|
|
|
return e.JSONPretty(http.StatusOK, files, " ")
|
|
}
|
|
|
|
func Stream(e echo.Context, directory, url string) error {
|
|
files, err := fs.Files(directory, url)
|
|
path := e.QueryParam("path")
|
|
|
|
if err != nil {
|
|
return e.JSON(http.StatusInternalServerError, ApiError{Error: fmt.Sprintf("%s", err)})
|
|
}
|
|
|
|
if path == "" {
|
|
return e.JSON(http.StatusBadRequest, ApiError{Error: "\"path\" query param is missing"})
|
|
}
|
|
|
|
for _, file := range files {
|
|
if file.RelativePath == path {
|
|
e.Response().Header().Del("Content-Length")
|
|
http.ServeFile(e.Response(), e.Request(), file.Path)
|
|
}
|
|
}
|
|
|
|
return e.JSON(http.StatusNotFound, ApiError{Error: "file not found"})
|
|
}
|