diff --git a/directories.go b/directories.go index 09f6fb9..d07d7c8 100644 --- a/directories.go +++ b/directories.go @@ -3,6 +3,7 @@ package owl import ( "os" "path/filepath" + "strings" ) func dirExists(path string) bool { @@ -38,3 +39,24 @@ func walkDir(path string) []string { }) return files } + +func toDirectoryName(name string) string { + name = strings.ToLower(strings.ReplaceAll(name, " ", "-")) + // remove all non-alphanumeric characters + name = strings.Map(func(r rune) rune { + if r >= 'a' && r <= 'z' { + return r + } + if r >= 'A' && r <= 'Z' { + return r + } + if r >= '0' && r <= '9' { + return r + } + if r == '-' { + return r + } + return -1 + }, name) + return name +} diff --git a/user.go b/user.go index 3de6939..181e75c 100644 --- a/user.go +++ b/user.go @@ -142,8 +142,7 @@ func (user User) GetPost(id string) (Post, error) { } func (user User) CreateNewPost(title string, draft bool) (Post, error) { - timestamp := time.Now().UTC().Unix() - folder_name := fmt.Sprintf("%d-%s", timestamp, title) + folder_name := toDirectoryName(title) post_dir := path.Join(user.Dir(), "public", folder_name) // if post already exists, add -n to the end of the name @@ -151,7 +150,7 @@ func (user User) CreateNewPost(title string, draft bool) (Post, error) { for { if dirExists(post_dir) { i++ - folder_name = fmt.Sprintf("%d-%s-%d", timestamp, title, i) + folder_name = toDirectoryName(fmt.Sprintf("%s-%d", title, i)) post_dir = path.Join(user.Dir(), "public", folder_name) } else { break diff --git a/user_test.go b/user_test.go index 6b4e1a0..e833e6e 100644 --- a/user_test.go +++ b/user_test.go @@ -317,3 +317,11 @@ func TestAvatarSetIfFileExist(t *testing.T) { t.Error("Avatar should not be empty") } } + +func TestPostNameIllegalFileName(t *testing.T) { + user := getTestUser() + _, err := user.CreateNewPost("testpost?///", false) + if err != nil { + t.Error("Should not have failed") + } +}