2022-06-27 04:38:09 +04:00
|
|
|
package files
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/url"
|
2022-06-28 06:13:44 +04:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2022-06-27 04:38:09 +04:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const FileDateFormat = "2006-01-02 15:04:05 MST"
|
|
|
|
|
2023-09-20 04:07:24 +04:00
|
|
|
type DirStat struct {
|
2022-06-27 04:38:09 +04:00
|
|
|
Files int64
|
|
|
|
FilesSize string
|
|
|
|
Directories int64
|
|
|
|
}
|
|
|
|
|
|
|
|
type DirEntry struct {
|
|
|
|
Name string
|
|
|
|
Link string
|
|
|
|
Datetime time.Time
|
|
|
|
Size string
|
|
|
|
}
|
|
|
|
|
2023-09-20 04:07:24 +04:00
|
|
|
func ScanDirectory(path, urlBase string) (entries []DirEntry, stats DirStat, err error) {
|
2022-12-17 22:44:29 +04:00
|
|
|
dir, err := os.ReadDir(path)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-09-20 04:55:38 +04:00
|
|
|
var dirEntries []DirEntry = make([]DirEntry, 0)
|
|
|
|
var fileEntries []DirEntry = make([]DirEntry, 0)
|
|
|
|
var totalFilesSize int64 = 0
|
|
|
|
|
2022-12-17 22:44:29 +04:00
|
|
|
for _, ent := range dir {
|
|
|
|
entry, _ := ent.Info()
|
2022-06-27 04:38:09 +04:00
|
|
|
|
2022-06-28 06:13:44 +04:00
|
|
|
var isDirLink bool
|
2022-12-17 22:44:29 +04:00
|
|
|
if entry.Mode().Type()&os.ModeSymlink != 0 {
|
2022-06-28 06:13:44 +04:00
|
|
|
if slp, err := filepath.EvalSymlinks(filepath.Join(path, entry.Name())); err == nil {
|
|
|
|
lStat, _ := os.Lstat(slp)
|
|
|
|
isDirLink = lStat.IsDir()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if entry.IsDir() || isDirLink {
|
2022-06-27 04:38:09 +04:00
|
|
|
dirEntries = append(dirEntries, DirEntry{
|
2022-06-27 22:50:33 +04:00
|
|
|
Name: entry.Name(),
|
|
|
|
Link: url.PathEscape(entry.Name()) + "/",
|
|
|
|
Datetime: entry.ModTime(),
|
2022-06-27 04:38:09 +04:00
|
|
|
Size: "DIR",
|
|
|
|
})
|
|
|
|
stats.Directories++
|
|
|
|
} else {
|
|
|
|
fileEntries = append(fileEntries, DirEntry{
|
2022-06-27 22:50:33 +04:00
|
|
|
Name: entry.Name(),
|
|
|
|
Link: "/file" + urlBase + url.PathEscape(entry.Name()),
|
|
|
|
Datetime: entry.ModTime(),
|
2022-12-17 22:46:17 +04:00
|
|
|
Size: convertFileSize(entry.Size()),
|
2022-06-27 04:38:09 +04:00
|
|
|
})
|
|
|
|
|
2022-06-27 22:50:33 +04:00
|
|
|
totalFilesSize += entry.Size()
|
2022-06-27 04:38:09 +04:00
|
|
|
stats.Files++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-17 22:46:17 +04:00
|
|
|
stats.FilesSize = convertFileSize(totalFilesSize)
|
2022-06-27 04:38:09 +04:00
|
|
|
|
|
|
|
entries = append(entries, dirEntries...)
|
|
|
|
entries = append(entries, fileEntries...)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|