GoBlog/editorFiles.go

68 lines
1.6 KiB
Go
Raw Normal View History

package main
import (
"net/http"
"sort"
2021-07-12 17:29:32 +00:00
2022-03-16 07:28:03 +00:00
"github.com/samber/lo"
)
func (a *goBlog) serveEditorFiles(w http.ResponseWriter, r *http.Request) {
2021-07-18 14:39:20 +00:00
// Get files
files, err := a.mediaFiles()
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
2021-07-18 14:39:20 +00:00
// Check if files at all
if len(files) == 0 {
a.render(w, r, a.renderEditorFiles, &renderData{
2022-01-27 17:17:44 +00:00
Data: &editorFilesRenderData{},
2021-07-18 14:39:20 +00:00
})
return
}
// Sort files time desc
sort.Slice(files, func(i, j int) bool {
return files[i].Time.After(files[j].Time)
})
2021-07-12 17:29:32 +00:00
// Find uses
2022-03-16 07:28:03 +00:00
fileNames := lo.Map(files, func(f *mediaFile, _ int) string {
2021-07-12 17:29:32 +00:00
return f.Name
2022-03-16 07:28:03 +00:00
})
2021-07-12 17:29:32 +00:00
uses, err := a.db.usesOfMediaFile(fileNames...)
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
// Serve HTML
a.render(w, r, a.renderEditorFiles, &renderData{
2022-01-27 17:17:44 +00:00
Data: &editorFilesRenderData{
files: files,
uses: uses,
},
})
}
func (a *goBlog) serveEditorFilesView(w http.ResponseWriter, r *http.Request) {
filename := r.FormValue("filename")
if filename == "" {
a.serveError(w, r, "No file selected", http.StatusBadRequest)
return
}
http.Redirect(w, r, a.mediaFileLocation(filename), http.StatusFound)
}
func (a *goBlog) serveEditorFilesDelete(w http.ResponseWriter, r *http.Request) {
filename := r.FormValue("filename")
if filename == "" {
a.serveError(w, r, "No file selected", http.StatusBadRequest)
return
}
if err := a.deleteMediaFile(filename); err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
_, bc := a.getBlog(r)
http.Redirect(w, r, bc.getRelativePath("/editor/files"), http.StatusFound)
}