takunomi-blog/postCollection.go
2017-11-17 15:12:04 +01:00

143 lines
2.7 KiB
Go

package main
import (
"fmt"
"golang.org/x/net/html"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
)
//Post : Is exported
type Post struct {
Date time.Time
Title string
URLTitle string
Content template.HTML
}
const layout = "2006-01-02"
var modTime time.Time
var postsCollection []Post
func InitializeCollection() {
postsCollection = nil
filepath.Walk("./posts", newPost)
fmt.Println(len(postsCollection))
for _, post := range postsCollection {
fmt.Println(post.Title)
}
}
func AcquirePosts(duration time.Duration) {
for {
if isFolderModified() == true {
postsCollection = nil
filepath.Walk("./posts", newPost)
}
time.Sleep(duration * time.Second)
}
}
func isFolderModified() bool {
f, err := os.Open("./posts")
if err != nil {
fmt.Println("file-error here: \n", f)
return false
}
info, err := f.Stat()
if err != nil {
fmt.Println("info here: \n", info)
return false
}
_modTime := info.ModTime()
if modTime != _modTime {
modTime = _modTime
return true
}
return false
}
func newPost(path string, f os.FileInfo, err error) error {
content, err := ioutil.ReadFile(path)
if err != nil {
fmt.Println(err)
//return err
}
title := strings.Replace(path, "posts/", "", -1)
if title == ".DS_Store" {
return nil
}
s := string(content)
doc, _ := html.Parse(strings.NewReader(s))
var p = Post{
getDate(doc),
title,
strings.Replace(title, " ", "-", -1),
template.HTML(string(content[:len(content)])),
}
//insertPostAccordingToDate(p, postsCollection)
postsCollection = insertPostAccordingToDate(p, postsCollection)
return nil
}
func getDate(n *html.Node) time.Time {
var t time.Time
if n.Type == html.ElementNode && n.Data == "time" {
for _, a := range n.Attr {
if a.Key == "datetime" {
t, _ = time.Parse(layout, a.Val)
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
t = getDate(c)
}
return t
}
func getNewestPosts(numberOfPosts int) []Post {
var posts []Post
if len(postsCollection) == 0 {
return []Post{}
}
for i := numberOfPosts; i > 0; i-- {
post := postsCollection[i]
posts = append(posts, getPostByURLTitle(post.URLTitle))
}
return posts
}
func getPostByURLTitle(title string) Post {
for _, post := range postsCollection {
if post.URLTitle == title {
return post
}
}
return Post{}
}
func insertPostAccordingToDate(post Post, arr []Post) []Post {
for i, p := range arr {
if p.Date.After(post.Date) {
s := make([]Post, len(arr)+1, cap(arr)+1)
copy(s[:], arr[:]) //make a copy of the slice
copy(s[i+1:], arr[i:]) //move the upper part of the slice ahead, creating a hole
s[i] = post //insert new element into hole
}
}
arr = append(arr, post)
return arr
}