s1llyw0rdz/model/status.go
2022-02-19 08:53:38 +01:00

79 lines
1.7 KiB
Go

package model
import (
"errors"
"fmt"
"html"
"html/template"
"regexp"
"strings"
"time"
)
type Status struct {
Id int64
User string
Content string
Face string
CreatedAt time.Time
}
var urlRegexp = regexp.MustCompile(`https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)`)
func (s Status) ContentDisplay() string {
content := html.EscapeString(s.Content)
if urlRegexp.MatchString(s.Content) {
matches := urlRegexp.FindAllStringSubmatch(s.Content, -1)
for _, m := range matches {
url := m[0]
content = strings.Replace(content, url, fmt.Sprintf("<a href=\"%s\" target=\"_blank\">%s</a>", url, url), 1)
}
}
return content
}
func (s Status) ContentHtml() template.HTML {
return template.HTML(s.ContentDisplay())
}
func (s Status) Validate() error {
if len(s.Content) == 0 {
return errors.New("content is empty")
}
return nil
}
func (s Status) Date() string {
return s.CreatedAt.Format("2006-01-02")
}
func (s Status) TimeAgo() string {
// Taken from flounder.online <3
// https://github.com/alexwennerberg/flounder
d := time.Since(s.CreatedAt)
if d.Seconds() < 60 {
seconds := int(d.Seconds())
if seconds == 1 {
return "1 second ago"
}
return fmt.Sprintf("%d seconds ago", seconds)
} else if d.Minutes() < 60 {
minutes := int(d.Minutes())
if minutes == 1 {
return "1 minute ago"
}
return fmt.Sprintf("%d minutes ago", minutes)
} else if d.Hours() < 24 {
hours := int(d.Hours())
if hours == 1 {
return "1 hour ago"
}
return fmt.Sprintf("%d hours ago", hours)
} else {
days := int(d.Hours()) / 24
if days == 1 {
return "1 day ago"
}
return fmt.Sprintf("%d days ago", days)
}
}