s1llyw0rdz/model/status.go

87 lines
2 KiB
Go
Raw Normal View History

2021-11-22 08:05:57 +00:00
package model
import (
"errors"
2021-11-22 17:12:07 +00:00
"fmt"
2022-02-19 07:53:38 +00:00
"html"
"html/template"
"regexp"
"strings"
2021-11-22 08:05:57 +00:00
"time"
)
type Status struct {
Id int64
User string
2021-11-22 17:12:07 +00:00
Content string
2021-11-30 20:50:10 +00:00
Face string
2021-11-22 08:05:57 +00:00
CreatedAt time.Time
}
2022-02-19 07:53:38 +00:00
var urlRegexp = regexp.MustCompile(`https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)`)
2022-02-24 14:44:58 +00:00
var userRegexp = regexp.MustCompile(`@([a-z0-9-_]+)\b`)
2022-02-19 07:53:38 +00:00
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)
}
}
2022-02-24 14:44:58 +00:00
if userRegexp.MatchString(s.Content) {
matches := userRegexp.FindAllStringSubmatch(s.Content, -1)
for _, m := range matches {
content = strings.Replace(content, m[0], fmt.Sprintf("<a href=\"https://status.cafe/users/%s\" target=\"_blank\">%s</a>", m[1], m[0]), 1)
}
}
2022-02-19 07:53:38 +00:00
return content
}
func (s Status) ContentHtml() template.HTML {
return template.HTML(s.ContentDisplay())
}
2021-11-22 08:05:57 +00:00
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")
}
2021-11-22 17:12:07 +00:00
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)
}
}