filebrowser/handlers/search.go

82 lines
1.6 KiB
Go
Raw Normal View History

2016-11-01 15:00:36 +00:00
package handlers
import (
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gorilla/websocket"
"github.com/hacdias/caddy-filemanager/config"
)
2016-11-01 15:06:44 +00:00
// Search ...
2016-11-01 15:00:36 +00:00
func Search(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
// Upgrades the connection to a websocket and checks for errors.
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return 0, err
}
defer conn.Close()
2016-11-01 15:06:44 +00:00
var (
search string
message []byte
)
2016-11-01 15:00:36 +00:00
2017-05-06 20:47:38 +00:00
caseInsensitive := (r.URL.Query().Get("insensitive") == "true")
2016-11-01 15:00:36 +00:00
// Starts an infinite loop until a valid command is captured.
for {
2016-11-01 15:06:44 +00:00
_, message, err = conn.ReadMessage()
2016-11-01 15:00:36 +00:00
if err != nil {
return http.StatusInternalServerError, err
}
if len(message) != 0 {
search = string(message)
break
}
}
2017-05-06 20:47:38 +00:00
if caseInsensitive {
search = strings.ToLower(search)
}
2016-11-01 15:00:36 +00:00
scope := strings.Replace(r.URL.Path, c.BaseURL, "", 1)
scope = strings.TrimPrefix(scope, "/")
scope = "/" + scope
scope = u.Scope + scope
scope = strings.Replace(scope, "\\", "/", -1)
scope = filepath.Clean(scope)
err = filepath.Walk(scope, func(path string, f os.FileInfo, err error) error {
2017-05-06 20:47:38 +00:00
if caseInsensitive {
path = strings.ToLower(path)
}
2016-11-01 15:00:36 +00:00
if strings.Contains(path, search) {
2016-11-01 15:06:44 +00:00
if !u.Allowed(path) {
return nil
}
2016-11-01 15:00:36 +00:00
path = strings.TrimPrefix(path, scope)
path = strings.Replace(path, "\\", "/", -1)
path = strings.TrimPrefix(path, "/")
err = conn.WriteMessage(websocket.TextMessage, []byte(path))
if err != nil {
return err
}
}
return nil
})
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}