This commit is contained in:
Jan-Lukas Else 2020-10-06 20:04:07 +02:00
parent 95909420ba
commit d1ce3ed49c
4 changed files with 36 additions and 29 deletions

26
api.go
View File

@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strings"
) )
func apiPostCreate(w http.ResponseWriter, r *http.Request) { func apiPostCreate(w http.ResponseWriter, r *http.Request) {
@ -26,11 +27,11 @@ func apiPostCreate(w http.ResponseWriter, r *http.Request) {
} }
func apiPostCreateHugo(w http.ResponseWriter, r *http.Request) { func apiPostCreateHugo(w http.ResponseWriter, r *http.Request) {
blog := r.URL.Query().Get("blog")
path := r.URL.Query().Get("path") path := r.URL.Query().Get("path")
if path == "" { section := r.URL.Query().Get("section")
http.Error(w, "No path defined", http.StatusBadRequest) slug := r.URL.Query().Get("slug")
return alias := r.URL.Query().Get("alias")
}
defer func() { defer func() {
_ = r.Body.Close() _ = r.Body.Close()
}() }()
@ -39,16 +40,31 @@ func apiPostCreateHugo(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
post, err := parseHugoFile(string(bodyContent), path) post, aliases, err := parseHugoFile(string(bodyContent))
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
post.Blog = blog
post.Path = path
post.Section = section
post.Slug = slug
aliases = append(aliases, alias)
err = post.createOrReplace(false) err = post.createOrReplace(false)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
for _, alias := range aliases {
// Fix relativ paths
if !strings.HasPrefix(alias, "/") {
splittedPostPath := strings.Split(post.Path, "/")
alias = strings.TrimSuffix(post.Path, splittedPostPath[len(splittedPostPath)-1]) + alias
}
if alias != "" {
_ = createOrReplaceRedirect(alias, post.Path)
}
}
w.Header().Set("Location", appConfig.Server.PublicAddress+post.Path) w.Header().Set("Location", appConfig.Server.PublicAddress+post.Path)
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
} }

28
hugo.go
View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"errors"
"strconv" "strconv"
"strings" "strings"
@ -10,18 +9,13 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
func parseHugoFile(fileContent string, path string) (*Post, error) { func parseHugoFile(fileContent string) (post *Post, aliases []string, e error) {
// TODO: Add option to set blog, slug
if path == "" {
return nil, errors.New("empty path")
}
frontmatterSep := "---\n" frontmatterSep := "---\n"
frontmatter := "" frontmatter := ""
if split := strings.Split(fileContent, frontmatterSep); len(split) > 2 { if split := strings.Split(fileContent, frontmatterSep); len(split) > 2 {
frontmatter = split[1] frontmatter = split[1]
} }
post := &Post{ post = &Post{
Path: path,
Content: strings.TrimPrefix(fileContent, frontmatterSep+frontmatter+frontmatterSep), Content: strings.TrimPrefix(fileContent, frontmatterSep+frontmatter+frontmatterSep),
Parameters: map[string][]string{}, Parameters: map[string][]string{},
} }
@ -29,11 +23,11 @@ func parseHugoFile(fileContent string, path string) (*Post, error) {
meta := map[string]interface{}{} meta := map[string]interface{}{}
err := yaml.Unmarshal([]byte(frontmatter), &meta) err := yaml.Unmarshal([]byte(frontmatter), &meta)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
flat, err := flatten.Flatten(meta, "", flatten.DotStyle) flat, err := flatten.Flatten(meta, "", flatten.DotStyle)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
// Read dates // Read dates
post.Published = cast.ToString(flat["date"]) post.Published = cast.ToString(flat["date"])
@ -58,9 +52,7 @@ func parseHugoFile(fileContent string, path string) (*Post, error) {
post.Parameters[fm.Parameter] = values post.Parameters[fm.Parameter] = values
} }
} }
// Create redirects // Parse redirects
// TODO: Move redirect creation after post creation
var aliases []string
for fk, value := range flat { for fk, value := range flat {
if strings.HasPrefix(fk, "aliases") { if strings.HasPrefix(fk, "aliases") {
trimmed := strings.TrimPrefix(fk, "aliases") trimmed := strings.TrimPrefix(fk, "aliases")
@ -74,14 +66,6 @@ func parseHugoFile(fileContent string, path string) (*Post, error) {
} }
} }
} }
for _, alias := range aliases {
// Fix relativ paths
if !strings.HasPrefix(alias, "/") {
splittedPostPath := strings.Split(post.Path, "/")
alias = strings.TrimSuffix(post.Path, splittedPostPath[len(splittedPostPath)-1]) + alias
}
_ = createOrReplaceRedirect(alias, post.Path)
}
// Return post // Return post
return post, nil return post, aliases, nil
} }

View File

@ -51,16 +51,19 @@ func (p *Post) checkPost(new bool) error {
random := generateRandomString(now, 5) random := generateRandomString(now, 5)
p.Slug = fmt.Sprintf("%v-%02d-%02d-%v", now.Year(), int(now.Month()), now.Day(), random) p.Slug = fmt.Sprintf("%v-%02d-%02d-%v", now.Year(), int(now.Month()), now.Day(), random)
} }
published, _ := dateparse.ParseIn(p.Published, time.Local)
pathVars := struct { pathVars := struct {
BlogPath string BlogPath string
Year int Year int
Month int Month int
Day int
Slug string Slug string
Section string Section string
}{ }{
BlogPath: appConfig.Blogs[p.Blog].Path, BlogPath: appConfig.Blogs[p.Blog].Path,
Year: now.Year(), Year: published.Year(),
Month: int(now.Month()), Month: int(published.Month()),
Day: published.Day(),
Slug: p.Slug, Slug: p.Slug,
Section: p.Section, Section: p.Section,
} }

View File

@ -61,6 +61,10 @@ func createOrReplaceRedirect(from, to string) error {
if from == "" || to == "" { if from == "" || to == "" {
return errors.New("empty path") return errors.New("empty path")
} }
if from == to {
// Don't need a redirect
return nil
}
from = strings.TrimSuffix(from, "/") from = strings.TrimSuffix(from, "/")
startWritingToDb() startWritingToDb()
tx, err := appDb.Begin() tx, err := appDb.Begin()