owl-blogs/user.go

93 lines
1.9 KiB
Go
Raw Normal View History

2022-07-20 17:35:31 +00:00
package kiss
import (
"fmt"
2022-07-21 17:44:07 +00:00
"io/ioutil"
2022-07-20 17:35:31 +00:00
"os"
"path"
2022-07-23 15:19:47 +00:00
"strings"
2022-07-20 17:35:31 +00:00
"time"
)
type User struct {
repo Repository
name string
}
func (user User) Dir() string {
2022-07-24 14:19:21 +00:00
return path.Join(user.repo.UsersDir(), user.name)
2022-07-20 17:35:31 +00:00
}
2022-07-23 15:19:47 +00:00
func (user User) Path() string {
return "/" + user.name
}
func (user User) PostDir() string {
return path.Join(user.Dir(), "public")
}
2022-07-20 17:35:31 +00:00
func (user User) Name() string {
return user.name
}
2022-07-21 17:44:07 +00:00
func (user User) Posts() ([]string, error) {
2022-07-23 15:19:47 +00:00
postFiles := walkDir(path.Join(user.Dir(), "public"))
posts := make([]string, 0)
for _, id := range postFiles {
if strings.HasSuffix(id, "/index.md") {
posts = append(posts, id[:len(id)-9])
}
}
return posts, nil
2022-07-21 17:44:07 +00:00
}
func (user User) GetPost(id string) (Post, error) {
post := Post{user: user, id: id}
_, metaData := post.MarkdownData()
title := metaData["title"]
post.title = fmt.Sprint(title)
return post, nil
2022-07-20 19:12:18 +00:00
}
2022-07-21 17:02:37 +00:00
func (user User) CreateNewPost(title string) (Post, error) {
2022-07-20 17:35:31 +00:00
timestamp := time.Now().UTC().Unix()
folder_name := fmt.Sprintf("%d-%s", timestamp, title)
post_dir := path.Join(user.Dir(), "public", folder_name)
// if post already exists, add -n to the end of the name
i := 0
for {
if dirExists(post_dir) {
i++
folder_name = fmt.Sprintf("%d-%s-%d", timestamp, title, i)
post_dir = path.Join(user.Dir(), "public", folder_name)
} else {
break
}
}
2022-07-21 17:44:07 +00:00
post := Post{user: user, id: folder_name, title: title}
initial_content := ""
initial_content += "---\n"
initial_content += "title: " + title + "\n"
initial_content += "---\n"
initial_content += "\n"
initial_content += "Write your post here.\n"
2022-07-20 17:35:31 +00:00
// create post file
os.Mkdir(post_dir, 0755)
2022-07-21 17:02:37 +00:00
os.WriteFile(post.ContentFile(), []byte(initial_content), 0644)
return post, nil
2022-07-20 17:35:31 +00:00
}
2022-07-21 17:44:07 +00:00
func (user User) Template() (string, error) {
// load base.html
path := path.Join(user.Dir(), "meta", "base.html")
base_html, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return string(base_html), nil
}