update
This commit is contained in:
parent
22e0ad0831
commit
06c1a412a6
|
@ -8,7 +8,7 @@
|
||||||
{{ else if eq .Type "video" }}
|
{{ else if eq .Type "video" }}
|
||||||
|
|
||||||
{{ else}}
|
{{ else}}
|
||||||
<pre>{{ .Content }}</pre>
|
<pre>{{ .StringifyContent }}</pre>
|
||||||
{{ end }}
|
{{ end }}
|
||||||
</main>
|
</main>
|
||||||
{{ end }}
|
{{ end }}
|
||||||
|
|
|
@ -3,7 +3,6 @@ package config
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
@ -23,9 +22,7 @@ type Config struct {
|
||||||
Token string // Anti CSRF token
|
Token string // Anti CSRF token
|
||||||
HugoEnabled bool // Enables the Hugo plugin for File Manager
|
HugoEnabled bool // Enables the Hugo plugin for File Manager
|
||||||
Users map[string]*User
|
Users map[string]*User
|
||||||
WebDav bool
|
|
||||||
WebDavURL string
|
WebDavURL string
|
||||||
WebDavHandler *webdav.Handler
|
|
||||||
CurrentUser *User
|
CurrentUser *User
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -48,8 +45,8 @@ func Parse(c *caddy.Controller) ([]Config, error) {
|
||||||
|
|
||||||
appendConfig := func(cfg Config) error {
|
appendConfig := func(cfg Config) error {
|
||||||
for _, c := range configs {
|
for _, c := range configs {
|
||||||
if c.PathScope == cfg.PathScope {
|
if c.Scope == cfg.Scope {
|
||||||
return fmt.Errorf("duplicate file managing config for %s", c.PathScope)
|
return fmt.Errorf("duplicate file managing config for %s", c.Scope)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
configs = append(configs, cfg)
|
configs = append(configs, cfg)
|
||||||
|
@ -59,8 +56,8 @@ func Parse(c *caddy.Controller) ([]Config, error) {
|
||||||
for c.Next() {
|
for c.Next() {
|
||||||
// Initialize the configuration with the default settings
|
// Initialize the configuration with the default settings
|
||||||
cfg := Config{User: &User{}}
|
cfg := Config{User: &User{}}
|
||||||
cfg.PathScope = "."
|
cfg.Scope = "."
|
||||||
cfg.Root = http.Dir(cfg.PathScope)
|
cfg.FileSystem = webdav.Dir(cfg.Scope)
|
||||||
cfg.BaseURL = ""
|
cfg.BaseURL = ""
|
||||||
cfg.FrontMatter = "yaml"
|
cfg.FrontMatter = "yaml"
|
||||||
cfg.HugoEnabled = false
|
cfg.HugoEnabled = false
|
||||||
|
@ -69,7 +66,6 @@ func Parse(c *caddy.Controller) ([]Config, error) {
|
||||||
cfg.AllowEdit = true
|
cfg.AllowEdit = true
|
||||||
cfg.AllowNew = true
|
cfg.AllowNew = true
|
||||||
cfg.Commands = []string{"git", "svn", "hg"}
|
cfg.Commands = []string{"git", "svn", "hg"}
|
||||||
cfg.WebDav = true
|
|
||||||
cfg.Rules = []*Rule{&Rule{
|
cfg.Rules = []*Rule{&Rule{
|
||||||
Regex: true,
|
Regex: true,
|
||||||
Allow: false,
|
Allow: false,
|
||||||
|
@ -121,9 +117,9 @@ func Parse(c *caddy.Controller) ([]Config, error) {
|
||||||
return configs, c.ArgErr()
|
return configs, c.ArgErr()
|
||||||
}
|
}
|
||||||
|
|
||||||
user.PathScope = c.Val()
|
user.Scope = c.Val()
|
||||||
user.PathScope = strings.TrimSuffix(user.PathScope, "/")
|
user.Scope = strings.TrimSuffix(user.Scope, "/")
|
||||||
user.Root = http.Dir(user.PathScope)
|
user.FileSystem = webdav.Dir(user.Scope)
|
||||||
case "styles":
|
case "styles":
|
||||||
if !c.NextArg() {
|
if !c.NextArg() {
|
||||||
return configs, c.ArgErr()
|
return configs, c.ArgErr()
|
||||||
|
@ -227,16 +223,16 @@ func Parse(c *caddy.Controller) ([]Config, error) {
|
||||||
user.AllowNew = cfg.AllowEdit
|
user.AllowNew = cfg.AllowEdit
|
||||||
user.Commands = cfg.Commands
|
user.Commands = cfg.Commands
|
||||||
user.FrontMatter = cfg.FrontMatter
|
user.FrontMatter = cfg.FrontMatter
|
||||||
user.PathScope = cfg.PathScope
|
user.Scope = cfg.Scope
|
||||||
user.Root = cfg.Root
|
user.FileSystem = cfg.FileSystem
|
||||||
user.Rules = cfg.Rules
|
user.Rules = cfg.Rules
|
||||||
user.StyleSheet = cfg.StyleSheet
|
user.StyleSheet = cfg.StyleSheet
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg.WebDavHandler = &webdav.Handler{
|
cfg.Handler = &webdav.Handler{
|
||||||
Prefix: cfg.WebDavURL,
|
Prefix: cfg.WebDavURL,
|
||||||
FileSystem: webdav.Dir(cfg.PathScope),
|
FileSystem: cfg.FileSystem,
|
||||||
LockSystem: webdav.NewMemLS(),
|
LockSystem: webdav.NewMemLS(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,14 +1,16 @@
|
||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/net/webdav"
|
||||||
)
|
)
|
||||||
|
|
||||||
// User contains the configuration for each user
|
// User contains the configuration for each user
|
||||||
type User struct {
|
type User struct {
|
||||||
PathScope string `json:"-"` // Path the user have access
|
Scope string `json:"-"` // Path the user have access
|
||||||
Root http.FileSystem `json:"-"` // The virtual file system the user have access
|
FileSystem webdav.FileSystem `json:"-"` // The virtual file system the user have access
|
||||||
|
Handler *webdav.Handler `json:"-"` // The WebDav HTTP Handler
|
||||||
StyleSheet string `json:"-"` // Costum stylesheet
|
StyleSheet string `json:"-"` // Costum stylesheet
|
||||||
FrontMatter string `json:"-"` // Default frontmatter to save files in
|
FrontMatter string `json:"-"` // Default frontmatter to save files in
|
||||||
AllowNew bool // Can create files and folders
|
AllowNew bool // Can create files and folders
|
||||||
|
|
|
@ -1,299 +0,0 @@
|
||||||
package directory
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/dustin/go-humanize"
|
|
||||||
"github.com/hacdias/caddy-filemanager/config"
|
|
||||||
p "github.com/hacdias/caddy-filemanager/page"
|
|
||||||
"github.com/hacdias/caddy-filemanager/utils/errors"
|
|
||||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Info is the information about a particular file or directory
|
|
||||||
type Info struct {
|
|
||||||
IsDir bool
|
|
||||||
Name string
|
|
||||||
Size int64
|
|
||||||
URL string
|
|
||||||
Path string // The relative Path of the file/directory relative to Caddyfile.
|
|
||||||
RootPath string // The Path of the file/directory on http.FileSystem.
|
|
||||||
ModTime time.Time
|
|
||||||
Mode os.FileMode
|
|
||||||
Mimetype string
|
|
||||||
Content string
|
|
||||||
Raw []byte
|
|
||||||
Type string
|
|
||||||
UserAllowed bool // Indicates if the user has permissions to open this directory
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetInfo gets the file information and, in case of error, returns the
|
|
||||||
// respective HTTP error code
|
|
||||||
func GetInfo(url *url.URL, c *config.Config, u *config.User) (*Info, int, error) {
|
|
||||||
var err error
|
|
||||||
|
|
||||||
rootPath := strings.Replace(url.Path, c.BaseURL, "", 1)
|
|
||||||
rootPath = strings.TrimPrefix(rootPath, "/")
|
|
||||||
rootPath = "/" + rootPath
|
|
||||||
|
|
||||||
relpath := u.PathScope + rootPath
|
|
||||||
relpath = strings.Replace(relpath, "\\", "/", -1)
|
|
||||||
relpath = filepath.Clean(relpath)
|
|
||||||
|
|
||||||
file := &Info{
|
|
||||||
URL: url.Path,
|
|
||||||
RootPath: rootPath,
|
|
||||||
Path: relpath,
|
|
||||||
}
|
|
||||||
f, err := u.Root.Open(rootPath)
|
|
||||||
if err != nil {
|
|
||||||
return file, errors.ToHTTPCode(err), err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
info, err := f.Stat()
|
|
||||||
if err != nil {
|
|
||||||
return file, errors.ToHTTPCode(err), err
|
|
||||||
}
|
|
||||||
|
|
||||||
file.IsDir = info.IsDir()
|
|
||||||
file.ModTime = info.ModTime()
|
|
||||||
file.Name = info.Name()
|
|
||||||
file.Size = info.Size()
|
|
||||||
return file, 0, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetExtendedInfo is used to get extra parameters for FileInfo struct
|
|
||||||
func (i *Info) GetExtendedInfo() error {
|
|
||||||
err := i.Read()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
i.Type = SimplifyMimeType(i.Mimetype)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read is used to read a file and store its content
|
|
||||||
func (i *Info) Read() error {
|
|
||||||
raw, err := ioutil.ReadFile(i.Path)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
i.Mimetype = http.DetectContentType(raw)
|
|
||||||
i.Content = string(raw)
|
|
||||||
i.Raw = raw
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// HumanSize returns the size of the file as a human-readable string
|
|
||||||
// in IEC format (i.e. power of 2 or base 1024).
|
|
||||||
func (i Info) HumanSize() string {
|
|
||||||
return humanize.IBytes(uint64(i.Size))
|
|
||||||
}
|
|
||||||
|
|
||||||
// HumanModTime returns the modified time of the file as a human-readable string.
|
|
||||||
func (i Info) HumanModTime(format string) string {
|
|
||||||
return i.ModTime.Format(format)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ServeAsHTML is used to serve single file pages
|
|
||||||
func (i *Info) ServeAsHTML(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
|
|
||||||
if i.IsDir {
|
|
||||||
return i.serveListing(w, r, c, u)
|
|
||||||
}
|
|
||||||
|
|
||||||
return i.serveSingleFile(w, r, c, u)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Info) serveSingleFile(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
|
|
||||||
err := i.GetExtendedInfo()
|
|
||||||
if err != nil {
|
|
||||||
return errors.ToHTTPCode(err), err
|
|
||||||
}
|
|
||||||
|
|
||||||
if i.Type == "blob" {
|
|
||||||
http.Redirect(w, r, c.AddrPath+r.URL.Path+"?download=true", http.StatusTemporaryRedirect)
|
|
||||||
return 0, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
page := &p.Page{
|
|
||||||
Info: &p.Info{
|
|
||||||
Name: i.Name,
|
|
||||||
Path: i.RootPath,
|
|
||||||
IsDir: false,
|
|
||||||
Data: i,
|
|
||||||
User: u,
|
|
||||||
Config: c,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if CanBeEdited(i.Name) && u.AllowEdit {
|
|
||||||
editor, err := i.GetEditor()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return http.StatusInternalServerError, err
|
|
||||||
}
|
|
||||||
|
|
||||||
page.Info.Data = editor
|
|
||||||
return page.PrintAsHTML(w, "frontmatter", "editor")
|
|
||||||
}
|
|
||||||
|
|
||||||
return page.PrintAsHTML(w, "single")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Info) serveListing(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
|
|
||||||
var err error
|
|
||||||
|
|
||||||
file, err := u.Root.Open(i.RootPath)
|
|
||||||
if err != nil {
|
|
||||||
return errors.ToHTTPCode(err), err
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
listing, err := i.loadDirectoryContents(file, r.URL.Path, u)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println(err)
|
|
||||||
switch {
|
|
||||||
case os.IsPermission(err):
|
|
||||||
return http.StatusForbidden, err
|
|
||||||
case os.IsExist(err):
|
|
||||||
return http.StatusGone, err
|
|
||||||
default:
|
|
||||||
return http.StatusInternalServerError, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
listing.Context = httpserver.Context{
|
|
||||||
Root: c.Root,
|
|
||||||
Req: r,
|
|
||||||
URL: r.URL,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Copy the query values into the Listing struct
|
|
||||||
var limit int
|
|
||||||
listing.Sort, listing.Order, limit, err = handleSortOrder(w, r, c.PathScope)
|
|
||||||
if err != nil {
|
|
||||||
return http.StatusBadRequest, err
|
|
||||||
}
|
|
||||||
|
|
||||||
listing.applySort()
|
|
||||||
|
|
||||||
if limit > 0 && limit <= len(listing.Items) {
|
|
||||||
listing.Items = listing.Items[:limit]
|
|
||||||
listing.ItemsLimitedTo = limit
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
|
||||||
marsh, err := json.Marshal(listing.Items)
|
|
||||||
if err != nil {
|
|
||||||
return http.StatusInternalServerError, err
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
||||||
if _, err := w.Write(marsh); err != nil {
|
|
||||||
return http.StatusInternalServerError, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return http.StatusOK, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
page := &p.Page{
|
|
||||||
Info: &p.Info{
|
|
||||||
Name: listing.Name,
|
|
||||||
Path: i.RootPath,
|
|
||||||
IsDir: true,
|
|
||||||
User: u,
|
|
||||||
Config: c,
|
|
||||||
Data: listing,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.Header.Get("Minimal") == "true" {
|
|
||||||
page.Minimal = true
|
|
||||||
}
|
|
||||||
|
|
||||||
return page.PrintAsHTML(w, "listing")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i Info) loadDirectoryContents(file http.File, path string, u *config.User) (*Listing, error) {
|
|
||||||
files, err := file.Readdir(-1)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
listing := directoryListing(files, i.RootPath, path, u)
|
|
||||||
return &listing, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func directoryListing(files []os.FileInfo, urlPath string, basePath string, u *config.User) Listing {
|
|
||||||
var (
|
|
||||||
fileinfos []Info
|
|
||||||
dirCount, fileCount int
|
|
||||||
)
|
|
||||||
|
|
||||||
for _, f := range files {
|
|
||||||
name := f.Name()
|
|
||||||
|
|
||||||
if f.IsDir() {
|
|
||||||
name += "/"
|
|
||||||
dirCount++
|
|
||||||
} else {
|
|
||||||
fileCount++
|
|
||||||
}
|
|
||||||
|
|
||||||
// Absolute URL
|
|
||||||
url := url.URL{Path: basePath + name}
|
|
||||||
fileinfos = append(fileinfos, Info{
|
|
||||||
IsDir: f.IsDir(),
|
|
||||||
Name: f.Name(),
|
|
||||||
Size: f.Size(),
|
|
||||||
URL: url.String(),
|
|
||||||
ModTime: f.ModTime().UTC(),
|
|
||||||
Mode: f.Mode(),
|
|
||||||
UserAllowed: u.Allowed(url.String()),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return Listing{
|
|
||||||
Name: path.Base(urlPath),
|
|
||||||
Path: urlPath,
|
|
||||||
Items: fileinfos,
|
|
||||||
NumDirs: dirCount,
|
|
||||||
NumFiles: fileCount,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SimplifyMimeType returns the base type of a file
|
|
||||||
func SimplifyMimeType(name string) string {
|
|
||||||
if strings.HasPrefix(name, "video") {
|
|
||||||
return "video"
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(name, "audio") {
|
|
||||||
return "audio"
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(name, "image") {
|
|
||||||
return "image"
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(name, "text") {
|
|
||||||
return "text"
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(name, "application/javascript") {
|
|
||||||
return "text"
|
|
||||||
}
|
|
||||||
|
|
||||||
return "blob"
|
|
||||||
}
|
|
|
@ -1,4 +1,4 @@
|
||||||
package directory
|
package filemanager
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
@ -18,10 +18,10 @@ type Editor struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetEditor gets the editor based on a FileInfo struct
|
// GetEditor gets the editor based on a FileInfo struct
|
||||||
func (i *Info) GetEditor() (*Editor, error) {
|
func (i *FileInfo) GetEditor() (*Editor, error) {
|
||||||
// Create a new editor variable and set the mode
|
// Create a new editor variable and set the mode
|
||||||
editor := new(Editor)
|
editor := new(Editor)
|
||||||
editor.Mode = strings.TrimPrefix(filepath.Ext(i.Name), ".")
|
editor.Mode = strings.TrimPrefix(filepath.Ext(i.Name()), ".")
|
||||||
|
|
||||||
switch editor.Mode {
|
switch editor.Mode {
|
||||||
case "md", "markdown", "mdown", "mmark":
|
case "md", "markdown", "mdown", "mmark":
|
||||||
|
@ -42,20 +42,20 @@ func (i *Info) GetEditor() (*Editor, error) {
|
||||||
// Handle the content depending on the file extension
|
// Handle the content depending on the file extension
|
||||||
switch editor.Mode {
|
switch editor.Mode {
|
||||||
case "markdown", "asciidoc", "rst":
|
case "markdown", "asciidoc", "rst":
|
||||||
if !HasFrontMatterRune(i.Raw) {
|
if !hasFrontMatterRune(i.Content) {
|
||||||
editor.Class = "content-only"
|
editor.Class = "content-only"
|
||||||
editor.Content = i.Content
|
editor.Content = i.StringifyContent()
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
// Starts a new buffer and parses the file using Hugo's functions
|
// Starts a new buffer and parses the file using Hugo's functions
|
||||||
buffer := bytes.NewBuffer(i.Raw)
|
buffer := bytes.NewBuffer(i.Content)
|
||||||
page, err = parser.ReadFrom(buffer)
|
page, err = parser.ReadFrom(buffer)
|
||||||
editor.Class = "complete"
|
editor.Class = "complete"
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
editor.Class = "content-only"
|
editor.Class = "content-only"
|
||||||
editor.Content = i.Content
|
editor.Content = i.StringifyContent()
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -67,35 +67,35 @@ func (i *Info) GetEditor() (*Editor, error) {
|
||||||
editor.Class = "frontmatter-only"
|
editor.Class = "frontmatter-only"
|
||||||
|
|
||||||
// Checks if the file already has the frontmatter rune and parses it
|
// Checks if the file already has the frontmatter rune and parses it
|
||||||
if HasFrontMatterRune(i.Raw) {
|
if hasFrontMatterRune(i.Content) {
|
||||||
editor.FrontMatter, _, err = frontmatter.Pretty(i.Raw)
|
editor.FrontMatter, _, err = frontmatter.Pretty(i.Content)
|
||||||
} else {
|
} else {
|
||||||
editor.FrontMatter, _, err = frontmatter.Pretty(AppendFrontMatterRune(i.Raw, editor.Mode))
|
editor.FrontMatter, _, err = frontmatter.Pretty(appendFrontMatterRune(i.Content, editor.Mode))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if there were any errors
|
// Check if there were any errors
|
||||||
if err != nil {
|
if err != nil {
|
||||||
editor.Class = "content-only"
|
editor.Class = "content-only"
|
||||||
editor.Content = i.Content
|
editor.Content = i.StringifyContent()
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
editor.Class = "content-only"
|
editor.Class = "content-only"
|
||||||
editor.Content = i.Content
|
editor.Content = i.StringifyContent()
|
||||||
}
|
}
|
||||||
|
|
||||||
return editor, nil
|
return editor, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// HasFrontMatterRune checks if the file has the frontmatter rune
|
// hasFrontMatterRune checks if the file has the frontmatter rune
|
||||||
func HasFrontMatterRune(file []byte) bool {
|
func hasFrontMatterRune(file []byte) bool {
|
||||||
return strings.HasPrefix(string(file), "---") ||
|
return strings.HasPrefix(string(file), "---") ||
|
||||||
strings.HasPrefix(string(file), "+++") ||
|
strings.HasPrefix(string(file), "+++") ||
|
||||||
strings.HasPrefix(string(file), "{")
|
strings.HasPrefix(string(file), "{")
|
||||||
}
|
}
|
||||||
|
|
||||||
// AppendFrontMatterRune appends the frontmatter rune to a file
|
// appendFrontMatterRune appends the frontmatter rune to a file
|
||||||
func AppendFrontMatterRune(frontmatter []byte, language string) []byte {
|
func appendFrontMatterRune(frontmatter []byte, language string) []byte {
|
||||||
switch language {
|
switch language {
|
||||||
case "yaml":
|
case "yaml":
|
||||||
return []byte("---\n" + string(frontmatter) + "\n---")
|
return []byte("---\n" + string(frontmatter) + "\n---")
|
||||||
|
@ -108,8 +108,8 @@ func AppendFrontMatterRune(frontmatter []byte, language string) []byte {
|
||||||
return frontmatter
|
return frontmatter
|
||||||
}
|
}
|
||||||
|
|
||||||
// CanBeEdited checks if the extension of a file is supported by the editor
|
// canBeEdited checks if the extension of a file is supported by the editor
|
||||||
func CanBeEdited(filename string) bool {
|
func canBeEdited(filename string) bool {
|
||||||
extensions := [...]string{
|
extensions := [...]string{
|
||||||
"md", "markdown", "mdown", "mmark",
|
"md", "markdown", "mdown", "mmark",
|
||||||
"asciidoc", "adoc", "ad",
|
"asciidoc", "adoc", "ad",
|
|
@ -16,9 +16,7 @@ import (
|
||||||
|
|
||||||
"github.com/hacdias/caddy-filemanager/assets"
|
"github.com/hacdias/caddy-filemanager/assets"
|
||||||
"github.com/hacdias/caddy-filemanager/config"
|
"github.com/hacdias/caddy-filemanager/config"
|
||||||
"github.com/hacdias/caddy-filemanager/directory"
|
|
||||||
"github.com/hacdias/caddy-filemanager/errors"
|
"github.com/hacdias/caddy-filemanager/errors"
|
||||||
"github.com/hacdias/caddy-filemanager/page"
|
|
||||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -33,7 +31,7 @@ type FileManager struct {
|
||||||
func (f FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
func (f FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||||
var (
|
var (
|
||||||
c *config.Config
|
c *config.Config
|
||||||
fi *directory.Info
|
fi *FileInfo
|
||||||
code int
|
code int
|
||||||
err error
|
err error
|
||||||
user *config.User
|
user *config.User
|
||||||
|
@ -78,7 +76,7 @@ func (f FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
c.WebDavHandler.ServeHTTP(w, r)
|
c.Handler.ServeHTTP(w, r)
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -96,7 +94,7 @@ func (f FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, err
|
||||||
|
|
||||||
if r.Method == http.MethodGet {
|
if r.Method == http.MethodGet {
|
||||||
// Gets the information of the directory/file
|
// Gets the information of the directory/file
|
||||||
fi, code, err = directory.GetInfo(r.URL, c, user)
|
fi, code, err = GetInfo(r.URL, c, user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if r.Method == http.MethodGet {
|
if r.Method == http.MethodGet {
|
||||||
return errors.PrintHTML(w, code, err)
|
return errors.PrintHTML(w, code, err)
|
||||||
|
@ -106,7 +104,7 @@ func (f FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, err
|
||||||
|
|
||||||
// If it's a dir and the path doesn't end with a trailing slash,
|
// If it's a dir and the path doesn't end with a trailing slash,
|
||||||
// redirect the user.
|
// redirect the user.
|
||||||
if fi.IsDir && !strings.HasSuffix(r.URL.Path, "/") {
|
if fi.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
|
||||||
http.Redirect(w, r, c.AddrPath+r.URL.Path+"/", http.StatusTemporaryRedirect)
|
http.Redirect(w, r, c.AddrPath+r.URL.Path+"/", http.StatusTemporaryRedirect)
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
@ -114,23 +112,23 @@ func (f FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, err
|
||||||
// Generate anti security token.
|
// Generate anti security token.
|
||||||
c.GenerateToken()
|
c.GenerateToken()
|
||||||
|
|
||||||
if !fi.IsDir {
|
if !fi.IsDir() {
|
||||||
query := r.URL.Query()
|
query := r.URL.Query()
|
||||||
if val, ok := query["raw"]; ok && val[0] == "true" {
|
if val, ok := query["raw"]; ok && val[0] == "true" {
|
||||||
r.URL.Path = strings.Replace(r.URL.Path, c.BaseURL, c.WebDavURL, 1)
|
r.URL.Path = strings.Replace(r.URL.Path, c.BaseURL, c.WebDavURL, 1)
|
||||||
c.WebDavHandler.ServeHTTP(w, r)
|
c.Handler.ServeHTTP(w, r)
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if val, ok := query["download"]; ok && val[0] == "true" {
|
if val, ok := query["download"]; ok && val[0] == "true" {
|
||||||
w.Header().Set("Content-Disposition", "attachment; filename="+fi.Name)
|
w.Header().Set("Content-Disposition", "attachment; filename="+fi.Name())
|
||||||
r.URL.Path = strings.Replace(r.URL.Path, c.BaseURL, c.WebDavURL, 1)
|
r.URL.Path = strings.Replace(r.URL.Path, c.BaseURL, c.WebDavURL, 1)
|
||||||
c.WebDavHandler.ServeHTTP(w, r)
|
c.Handler.ServeHTTP(w, r)
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
code, err := fi.ServeAsHTML(w, r, c, user)
|
code, err := fi.ServeHTTP(w, r, c, user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.PrintHTML(w, code, err)
|
return errors.PrintHTML(w, code, err)
|
||||||
}
|
}
|
||||||
|
@ -189,7 +187,7 @@ func command(w http.ResponseWriter, r *http.Request, c *config.Config, u *config
|
||||||
return http.StatusNotImplemented, nil
|
return http.StatusNotImplemented, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
path := strings.Replace(r.URL.Path, c.BaseURL, c.PathScope, 1)
|
path := strings.Replace(r.URL.Path, c.BaseURL, c.Scope, 1)
|
||||||
path = filepath.Clean(path)
|
path = filepath.Clean(path)
|
||||||
|
|
||||||
cmd := exec.Command(command[0], command[1:len(command)]...)
|
cmd := exec.Command(command[0], command[1:len(command)]...)
|
||||||
|
@ -200,6 +198,6 @@ func command(w http.ResponseWriter, r *http.Request, c *config.Config, u *config
|
||||||
return http.StatusInternalServerError, err
|
return http.StatusInternalServerError, err
|
||||||
}
|
}
|
||||||
|
|
||||||
page := &page.Page{Info: &page.Info{Data: string(output)}}
|
p := &page{pageInfo: &pageInfo{Data: string(output)}}
|
||||||
return page.PrintAsJSON(w)
|
return p.PrintAsJSON(w)
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,165 @@
|
||||||
|
package filemanager
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/ioutil"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
humanize "github.com/dustin/go-humanize"
|
||||||
|
"github.com/hacdias/caddy-filemanager/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FileInfo contains the information about a particular file or directory
|
||||||
|
type FileInfo struct {
|
||||||
|
os.FileInfo
|
||||||
|
URL string
|
||||||
|
Path string // Relative path to Caddyfile
|
||||||
|
VirtualPath string // Relative path to u.FileSystem
|
||||||
|
Mimetype string
|
||||||
|
Content []byte
|
||||||
|
Type string
|
||||||
|
UserAllowed bool // Indicates if the user has enough permissions
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetInfo gets the file information and, in case of error, returns the
|
||||||
|
// respective HTTP error code
|
||||||
|
func GetInfo(url *url.URL, c *config.Config, u *config.User) (*FileInfo, int, error) {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
i := &FileInfo{URL: url.Path}
|
||||||
|
i.VirtualPath = strings.Replace(url.Path, c.BaseURL, "", 1)
|
||||||
|
i.VirtualPath = strings.TrimPrefix(i.VirtualPath, "/")
|
||||||
|
i.VirtualPath = "/" + i.VirtualPath
|
||||||
|
|
||||||
|
i.Path = u.Scope + i.VirtualPath
|
||||||
|
i.Path = strings.Replace(i.Path, "\\", "/", -1)
|
||||||
|
i.Path = filepath.Clean(i.Path)
|
||||||
|
|
||||||
|
i.FileInfo, err = os.Stat(i.Path)
|
||||||
|
if err != nil {
|
||||||
|
code := http.StatusInternalServerError
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case os.IsPermission(err):
|
||||||
|
code = http.StatusForbidden
|
||||||
|
case os.IsNotExist(err):
|
||||||
|
code = http.StatusGone
|
||||||
|
case os.IsExist(err):
|
||||||
|
code = http.StatusGone
|
||||||
|
}
|
||||||
|
|
||||||
|
return i, code, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return i, 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *FileInfo) Read() error {
|
||||||
|
var err error
|
||||||
|
i.Content, err = ioutil.ReadFile(i.Path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Mimetype = http.DetectContentType(i.Content)
|
||||||
|
i.Type = SimplifyMimeType(i.Mimetype)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i FileInfo) StringifyContent() string {
|
||||||
|
return string(i.Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HumanSize returns the size of the file as a human-readable string
|
||||||
|
// in IEC format (i.e. power of 2 or base 1024).
|
||||||
|
func (i FileInfo) HumanSize() string {
|
||||||
|
return humanize.IBytes(uint64(i.Size()))
|
||||||
|
}
|
||||||
|
|
||||||
|
// HumanModTime returns the modified time of the file as a human-readable string.
|
||||||
|
func (i FileInfo) HumanModTime(format string) string {
|
||||||
|
return i.ModTime().Format(format)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *FileInfo) ServeHTTP(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
|
||||||
|
if i.IsDir() {
|
||||||
|
return i.serveListing(w, r, c, u)
|
||||||
|
}
|
||||||
|
|
||||||
|
return i.serveSingleFile(w, r, c, u)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *FileInfo) serveSingleFile(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
|
||||||
|
err := i.Read()
|
||||||
|
if err != nil {
|
||||||
|
code := http.StatusInternalServerError
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case os.IsPermission(err):
|
||||||
|
code = http.StatusForbidden
|
||||||
|
case os.IsNotExist(err):
|
||||||
|
code = http.StatusGone
|
||||||
|
case os.IsExist(err):
|
||||||
|
code = http.StatusGone
|
||||||
|
}
|
||||||
|
|
||||||
|
return code, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if i.Type == "blob" {
|
||||||
|
http.Redirect(
|
||||||
|
w, r,
|
||||||
|
c.AddrPath+r.URL.Path+"?download=true",
|
||||||
|
http.StatusTemporaryRedirect,
|
||||||
|
)
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p := &page{
|
||||||
|
pageInfo: &pageInfo{
|
||||||
|
Name: i.Name(),
|
||||||
|
Path: i.VirtualPath,
|
||||||
|
IsDir: false,
|
||||||
|
Data: i,
|
||||||
|
User: u,
|
||||||
|
Config: c,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if (canBeEdited(i.Name()) || i.Type == "text") && u.AllowEdit {
|
||||||
|
p.Data, err = i.GetEditor()
|
||||||
|
if err != nil {
|
||||||
|
return http.StatusInternalServerError, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return p.PrintAsHTML(w, "frontmatter", "editor")
|
||||||
|
}
|
||||||
|
|
||||||
|
return p.PrintAsHTML(w, "single")
|
||||||
|
}
|
||||||
|
|
||||||
|
func SimplifyMimeType(name string) string {
|
||||||
|
if strings.HasPrefix(name, "video") {
|
||||||
|
return "video"
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(name, "audio") {
|
||||||
|
return "audio"
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(name, "image") {
|
||||||
|
return "image"
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(name, "text") {
|
||||||
|
return "text"
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(name, "application/javascript") {
|
||||||
|
return "text"
|
||||||
|
}
|
||||||
|
|
||||||
|
return "blob"
|
||||||
|
}
|
|
@ -1,11 +1,18 @@
|
||||||
package directory
|
package filemanager
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/hacdias/caddy-filemanager/config"
|
||||||
|
"github.com/hacdias/caddy-filemanager/utils/errors"
|
||||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -16,7 +23,7 @@ type Listing struct {
|
||||||
// The full path of the request
|
// The full path of the request
|
||||||
Path string
|
Path string
|
||||||
// The items (files and folders) in the path
|
// The items (files and folders) in the path
|
||||||
Items []Info
|
Items []FileInfo
|
||||||
// The number of directories in the listing
|
// The number of directories in the listing
|
||||||
NumDirs int
|
NumDirs int
|
||||||
// The number of files (items that aren't directories) in the listing
|
// The number of files (items that aren't directories) in the listing
|
||||||
|
@ -77,15 +84,15 @@ func (l byName) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i]
|
||||||
|
|
||||||
// Treat upper and lower case equally
|
// Treat upper and lower case equally
|
||||||
func (l byName) Less(i, j int) bool {
|
func (l byName) Less(i, j int) bool {
|
||||||
if l.Items[i].IsDir && !l.Items[j].IsDir {
|
if l.Items[i].IsDir() && !l.Items[j].IsDir() {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
if !l.Items[i].IsDir && l.Items[j].IsDir {
|
if !l.Items[i].IsDir() && l.Items[j].IsDir() {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name)
|
return strings.ToLower(l.Items[i].Name()) < strings.ToLower(l.Items[j].Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
// By Size
|
// By Size
|
||||||
|
@ -94,11 +101,11 @@ func (l bySize) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i]
|
||||||
|
|
||||||
const directoryOffset = -1 << 31 // = math.MinInt32
|
const directoryOffset = -1 << 31 // = math.MinInt32
|
||||||
func (l bySize) Less(i, j int) bool {
|
func (l bySize) Less(i, j int) bool {
|
||||||
iSize, jSize := l.Items[i].Size, l.Items[j].Size
|
iSize, jSize := l.Items[i].Size(), l.Items[j].Size()
|
||||||
if l.Items[i].IsDir {
|
if l.Items[i].IsDir() {
|
||||||
iSize = directoryOffset + iSize
|
iSize = directoryOffset + iSize
|
||||||
}
|
}
|
||||||
if l.Items[j].IsDir {
|
if l.Items[j].IsDir() {
|
||||||
jSize = directoryOffset + jSize
|
jSize = directoryOffset + jSize
|
||||||
}
|
}
|
||||||
return iSize < jSize
|
return iSize < jSize
|
||||||
|
@ -107,7 +114,7 @@ func (l bySize) Less(i, j int) bool {
|
||||||
// By Time
|
// By Time
|
||||||
func (l byTime) Len() int { return len(l.Items) }
|
func (l byTime) Len() int { return len(l.Items) }
|
||||||
func (l byTime) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
|
func (l byTime) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
|
||||||
func (l byTime) Less(i, j int) bool { return l.Items[i].ModTime.Before(l.Items[j].ModTime) }
|
func (l byTime) Less(i, j int) bool { return l.Items[i].ModTime().Before(l.Items[j].ModTime()) }
|
||||||
|
|
||||||
// Add sorting method to "Listing"
|
// Add sorting method to "Listing"
|
||||||
// it will apply what's in ".Sort" and ".Order"
|
// it will apply what's in ".Sort" and ".Order"
|
||||||
|
@ -139,3 +146,121 @@ func (l Listing) applySort() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (i *FileInfo) serveListing(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
file, err := u.FileSystem.OpenFile(i.VirtualPath, os.O_RDONLY, 0)
|
||||||
|
if err != nil {
|
||||||
|
return errors.ToHTTPCode(err), err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
listing, err := i.loadDirectoryContents(file, r.URL.Path, u)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
switch {
|
||||||
|
case os.IsPermission(err):
|
||||||
|
return http.StatusForbidden, err
|
||||||
|
case os.IsExist(err):
|
||||||
|
return http.StatusGone, err
|
||||||
|
default:
|
||||||
|
return http.StatusInternalServerError, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
listing.Context = httpserver.Context{
|
||||||
|
Root: http.Dir(u.Scope),
|
||||||
|
Req: r,
|
||||||
|
URL: r.URL,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy the query values into the Listing struct
|
||||||
|
var limit int
|
||||||
|
listing.Sort, listing.Order, limit, err = handleSortOrder(w, r, c.Scope)
|
||||||
|
if err != nil {
|
||||||
|
return http.StatusBadRequest, err
|
||||||
|
}
|
||||||
|
|
||||||
|
listing.applySort()
|
||||||
|
|
||||||
|
if limit > 0 && limit <= len(listing.Items) {
|
||||||
|
listing.Items = listing.Items[:limit]
|
||||||
|
listing.ItemsLimitedTo = limit
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||||
|
marsh, err := json.Marshal(listing.Items)
|
||||||
|
if err != nil {
|
||||||
|
return http.StatusInternalServerError, err
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
if _, err := w.Write(marsh); err != nil {
|
||||||
|
return http.StatusInternalServerError, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return http.StatusOK, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
page := &page{
|
||||||
|
pageInfo: &pageInfo{
|
||||||
|
Name: listing.Name,
|
||||||
|
Path: i.VirtualPath,
|
||||||
|
IsDir: true,
|
||||||
|
User: u,
|
||||||
|
Config: c,
|
||||||
|
Data: listing,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.Header.Get("Minimal") == "true" {
|
||||||
|
page.Minimal = true
|
||||||
|
}
|
||||||
|
|
||||||
|
return page.PrintAsHTML(w, "listing")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i FileInfo) loadDirectoryContents(file http.File, path string, u *config.User) (*Listing, error) {
|
||||||
|
files, err := file.Readdir(-1)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
listing := directoryListing(files, i.VirtualPath, path, u)
|
||||||
|
return &listing, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func directoryListing(files []os.FileInfo, urlPath string, basePath string, u *config.User) Listing {
|
||||||
|
var (
|
||||||
|
fileinfos []FileInfo
|
||||||
|
dirCount, fileCount int
|
||||||
|
)
|
||||||
|
|
||||||
|
for _, f := range files {
|
||||||
|
name := f.Name()
|
||||||
|
|
||||||
|
if f.IsDir() {
|
||||||
|
name += "/"
|
||||||
|
dirCount++
|
||||||
|
} else {
|
||||||
|
fileCount++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Absolute URL
|
||||||
|
url := url.URL{Path: basePath + name}
|
||||||
|
fileinfos = append(fileinfos, FileInfo{
|
||||||
|
FileInfo: f,
|
||||||
|
URL: url.String(),
|
||||||
|
UserAllowed: u.Allowed(url.String()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return Listing{
|
||||||
|
Name: path.Base(urlPath),
|
||||||
|
Path: urlPath,
|
||||||
|
Items: fileinfos,
|
||||||
|
NumDirs: dirCount,
|
||||||
|
NumFiles: fileCount,
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package page
|
package filemanager
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
@ -13,14 +13,14 @@ import (
|
||||||
"github.com/hacdias/caddy-filemanager/utils/variables"
|
"github.com/hacdias/caddy-filemanager/utils/variables"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Page contains the informations and functions needed to show the page
|
// page contains the informations and functions needed to show the page
|
||||||
type Page struct {
|
type page struct {
|
||||||
*Info
|
*pageInfo
|
||||||
Minimal bool
|
Minimal bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Info contains the information of a page
|
// pageInfo contains the information of a page
|
||||||
type Info struct {
|
type pageInfo struct {
|
||||||
Name string
|
Name string
|
||||||
Path string
|
Path string
|
||||||
IsDir bool
|
IsDir bool
|
||||||
|
@ -31,7 +31,7 @@ type Info struct {
|
||||||
|
|
||||||
// BreadcrumbMap returns p.Path where every element is a map
|
// BreadcrumbMap returns p.Path where every element is a map
|
||||||
// of URLs and path segment names.
|
// of URLs and path segment names.
|
||||||
func (i Info) BreadcrumbMap() map[string]string {
|
func (i pageInfo) BreadcrumbMap() map[string]string {
|
||||||
result := map[string]string{}
|
result := map[string]string{}
|
||||||
|
|
||||||
if len(i.Path) == 0 {
|
if len(i.Path) == 0 {
|
||||||
|
@ -62,7 +62,7 @@ func (i Info) BreadcrumbMap() map[string]string {
|
||||||
}
|
}
|
||||||
|
|
||||||
// PreviousLink returns the path of the previous folder
|
// PreviousLink returns the path of the previous folder
|
||||||
func (i Info) PreviousLink() string {
|
func (i pageInfo) PreviousLink() string {
|
||||||
path := strings.TrimSuffix(i.Path, "/")
|
path := strings.TrimSuffix(i.Path, "/")
|
||||||
path = strings.TrimPrefix(path, "/")
|
path = strings.TrimPrefix(path, "/")
|
||||||
path = i.Config.AbsoluteURL + "/" + path
|
path = i.Config.AbsoluteURL + "/" + path
|
||||||
|
@ -76,7 +76,7 @@ func (i Info) PreviousLink() string {
|
||||||
}
|
}
|
||||||
|
|
||||||
// PrintAsHTML formats the page in HTML and executes the template
|
// PrintAsHTML formats the page in HTML and executes the template
|
||||||
func (p Page) PrintAsHTML(w http.ResponseWriter, templates ...string) (int, error) {
|
func (p page) PrintAsHTML(w http.ResponseWriter, templates ...string) (int, error) {
|
||||||
// Create the functions map, then the template, check for erros and
|
// Create the functions map, then the template, check for erros and
|
||||||
// execute the template if there aren't errors
|
// execute the template if there aren't errors
|
||||||
functions := template.FuncMap{
|
functions := template.FuncMap{
|
||||||
|
@ -124,7 +124,7 @@ func (p Page) PrintAsHTML(w http.ResponseWriter, templates ...string) (int, erro
|
||||||
}
|
}
|
||||||
|
|
||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
err := tpl.Execute(buf, p.Info)
|
err := tpl.Execute(buf, p.pageInfo)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return http.StatusInternalServerError, err
|
return http.StatusInternalServerError, err
|
||||||
|
@ -136,8 +136,8 @@ func (p Page) PrintAsHTML(w http.ResponseWriter, templates ...string) (int, erro
|
||||||
}
|
}
|
||||||
|
|
||||||
// PrintAsJSON prints the current page infromation in JSON
|
// PrintAsJSON prints the current page infromation in JSON
|
||||||
func (p Page) PrintAsJSON(w http.ResponseWriter) (int, error) {
|
func (p page) PrintAsJSON(w http.ResponseWriter) (int, error) {
|
||||||
marsh, err := json.Marshal(p.Info.Data)
|
marsh, err := json.Marshal(p.pageInfo.Data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return http.StatusInternalServerError, err
|
return http.StatusInternalServerError, err
|
||||||
}
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package directory
|
package filemanager
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
@ -15,7 +15,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
// Update is used to update a file that was edited
|
// Update is used to update a file that was edited
|
||||||
func (i *Info) Update(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
|
func (i *FileInfo) Update(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
|
||||||
var (
|
var (
|
||||||
data map[string]interface{}
|
data map[string]interface{}
|
||||||
file []byte
|
file []byte
|
||||||
|
@ -38,7 +38,7 @@ func (i *Info) Update(w http.ResponseWriter, r *http.Request, c *config.Config,
|
||||||
|
|
||||||
switch kind {
|
switch kind {
|
||||||
case "frontmatter-only":
|
case "frontmatter-only":
|
||||||
if file, code, err = ParseFrontMatterOnlyFile(data, i.Name); err != nil {
|
if file, code, err = parseFrontMatterOnlyFile(data, i.Name()); err != nil {
|
||||||
return http.StatusInternalServerError, err
|
return http.StatusInternalServerError, err
|
||||||
}
|
}
|
||||||
case "content-only":
|
case "content-only":
|
||||||
|
@ -46,7 +46,7 @@ func (i *Info) Update(w http.ResponseWriter, r *http.Request, c *config.Config,
|
||||||
mainContent = strings.TrimSpace(mainContent)
|
mainContent = strings.TrimSpace(mainContent)
|
||||||
file = []byte(mainContent)
|
file = []byte(mainContent)
|
||||||
case "complete":
|
case "complete":
|
||||||
if file, code, err = ParseCompleteFile(data, i.Name, u.FrontMatter); err != nil {
|
if file, code, err = parseCompleteFile(data, i.Name(), u.FrontMatter); err != nil {
|
||||||
return http.StatusInternalServerError, err
|
return http.StatusInternalServerError, err
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
|
@ -58,10 +58,10 @@ func (i *Info) Update(w http.ResponseWriter, r *http.Request, c *config.Config,
|
||||||
return code, nil
|
return code, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseFrontMatterOnlyFile parses a frontmatter only file
|
// parseFrontMatterOnlyFile parses a frontmatter only file
|
||||||
func ParseFrontMatterOnlyFile(data interface{}, filename string) ([]byte, int, error) {
|
func parseFrontMatterOnlyFile(data interface{}, filename string) ([]byte, int, error) {
|
||||||
frontmatter := strings.TrimPrefix(filepath.Ext(filename), ".")
|
frontmatter := strings.TrimPrefix(filepath.Ext(filename), ".")
|
||||||
f, code, err := ParseFrontMatter(data, frontmatter)
|
f, code, err := parseFrontMatter(data, frontmatter)
|
||||||
fString := string(f)
|
fString := string(f)
|
||||||
|
|
||||||
// If it's toml or yaml, strip frontmatter identifier
|
// If it's toml or yaml, strip frontmatter identifier
|
||||||
|
@ -79,8 +79,8 @@ func ParseFrontMatterOnlyFile(data interface{}, filename string) ([]byte, int, e
|
||||||
return f, code, err
|
return f, code, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseFrontMatter is the frontmatter parser
|
// parseFrontMatter is the frontmatter parser
|
||||||
func ParseFrontMatter(data interface{}, frontmatter string) ([]byte, int, error) {
|
func parseFrontMatter(data interface{}, frontmatter string) ([]byte, int, error) {
|
||||||
var mark rune
|
var mark rune
|
||||||
|
|
||||||
switch frontmatter {
|
switch frontmatter {
|
||||||
|
@ -103,8 +103,8 @@ func ParseFrontMatter(data interface{}, frontmatter string) ([]byte, int, error)
|
||||||
return f, http.StatusOK, nil
|
return f, http.StatusOK, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseCompleteFile parses a complete file
|
// parseCompleteFile parses a complete file
|
||||||
func ParseCompleteFile(data map[string]interface{}, filename string, frontmatter string) ([]byte, int, error) {
|
func parseCompleteFile(data map[string]interface{}, filename string, frontmatter string) ([]byte, int, error) {
|
||||||
mainContent := ""
|
mainContent := ""
|
||||||
|
|
||||||
if _, ok := data["content"]; ok {
|
if _, ok := data["content"]; ok {
|
||||||
|
@ -120,7 +120,7 @@ func ParseCompleteFile(data map[string]interface{}, filename string, frontmatter
|
||||||
data["date"] = data["date"].(string) + ":00"
|
data["date"] = data["date"].(string) + ":00"
|
||||||
}
|
}
|
||||||
|
|
||||||
front, code, err := ParseFrontMatter(data, frontmatter)
|
front, code, err := parseFrontMatter(data, frontmatter)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(frontmatter)
|
fmt.Println(frontmatter)
|
Loading…
Reference in New Issue