2016-06-10 19:54:19 +00:00
|
|
|
package filemanager
|
|
|
|
|
|
|
|
import (
|
2016-06-11 20:20:47 +00:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2016-06-10 19:54:19 +00:00
|
|
|
"os"
|
2016-06-11 20:20:47 +00:00
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2016-06-10 19:54:19 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/dustin/go-humanize"
|
|
|
|
)
|
|
|
|
|
2016-06-11 20:20:47 +00:00
|
|
|
// FileInfo is the information about a particular file or directory
|
2016-06-10 19:54:19 +00:00
|
|
|
type FileInfo struct {
|
|
|
|
IsDir bool
|
|
|
|
Name string
|
|
|
|
Size int64
|
|
|
|
URL string
|
|
|
|
ModTime time.Time
|
|
|
|
Mode os.FileMode
|
2016-06-11 20:20:47 +00:00
|
|
|
Path string
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetFileInfo gets the file information and, in case of error, returns the
|
|
|
|
// respective HTTP error code
|
|
|
|
func GetFileInfo(url *url.URL, c *Config) (*FileInfo, int, error) {
|
|
|
|
var err error
|
|
|
|
|
|
|
|
path := strings.Replace(url.Path, c.BaseURL, c.PathScope, 1)
|
|
|
|
path = filepath.Clean(path)
|
|
|
|
|
|
|
|
file := &FileInfo{Path: path}
|
|
|
|
f, err := c.Root.Open(path)
|
|
|
|
if err != nil {
|
|
|
|
return file, ErrorToHTTPCode(err), err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
info, err := f.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return file, ErrorToHTTPCode(err), err
|
|
|
|
}
|
|
|
|
|
|
|
|
file.IsDir = info.IsDir()
|
|
|
|
file.ModTime = info.ModTime()
|
|
|
|
file.Name = info.Name()
|
|
|
|
file.Size = info.Size()
|
|
|
|
file.URL = url.Path
|
|
|
|
|
|
|
|
return file, 0, nil
|
2016-06-10 19:54:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// HumanSize returns the size of the file as a human-readable string
|
|
|
|
// in IEC format (i.e. power of 2 or base 1024).
|
|
|
|
func (fi FileInfo) HumanSize() string {
|
|
|
|
return humanize.IBytes(uint64(fi.Size))
|
|
|
|
}
|
|
|
|
|
|
|
|
// HumanModTime returns the modified time of the file as a human-readable string.
|
|
|
|
func (fi FileInfo) HumanModTime(format string) string {
|
|
|
|
return fi.ModTime.Format(format)
|
|
|
|
}
|
2016-06-11 20:20:47 +00:00
|
|
|
|
|
|
|
// Delete handles the delete requests
|
|
|
|
func (fi FileInfo) Delete() (int, error) {
|
|
|
|
var err error
|
|
|
|
|
|
|
|
// If it's a directory remove all the contents inside
|
|
|
|
if fi.IsDir {
|
|
|
|
err = os.RemoveAll(fi.Path)
|
|
|
|
} else {
|
|
|
|
err = os.Remove(fi.Path)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return ErrorToHTTPCode(err), err
|
|
|
|
}
|
|
|
|
|
|
|
|
return http.StatusOK, nil
|
|
|
|
}
|