tilde.town/genblog.go

122 lines
2.0 KiB
Go
Raw Normal View History

2021-08-06 03:18:46 +00:00
package main
2021-08-06 07:31:25 +00:00
import (
"bytes"
2022-04-25 21:22:10 +00:00
_ "embed"
2021-08-06 07:31:25 +00:00
"encoding/json"
"fmt"
"os"
"os/exec"
2022-04-25 22:20:11 +00:00
"sort"
2021-08-06 07:31:25 +00:00
"text/template"
)
2022-04-25 22:20:11 +00:00
const statsPath = "/usr/local/bin/stats"
2021-08-06 07:31:25 +00:00
2022-04-25 21:22:10 +00:00
//go:embed blog.tmpl.html
var blogTmpl string
2021-08-06 07:31:25 +00:00
type newsEntry struct {
2022-04-25 22:20:11 +00:00
Title string // Title of entry
Pubdate string // Human readable date
Content string // HTML of entry
}
type User struct {
Username string
Default bool
2021-08-06 07:31:25 +00:00
}
type tildeData struct {
2022-04-25 22:20:11 +00:00
News []newsEntry
Users []User
ActiveUsers []string `json:"active_users"`
2021-08-06 07:31:25 +00:00
}
2022-04-25 22:20:11 +00:00
type ByName []User
func (n ByName) Len() int { return len(n) }
func (n ByName) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
func (n ByName) Less(i, j int) bool { return n[i].Username < n[j].Username }
2021-08-06 07:31:25 +00:00
func _main() error {
data, err := stats()
if err != nil {
return err
}
2022-04-25 22:20:11 +00:00
type tmplData struct {
News []newsEntry
Lights string
}
td := &tmplData{
News: data.News,
Lights: "",
}
sort.Sort(ByName(data.Users))
isActive := func(username string) bool {
for _, u := range data.ActiveUsers {
if u == username {
return true
}
}
return false
}
for _, u := range data.Users {
if isActive(u.Username) {
td.Lights += fmt.Sprintf("<a href=\"/~%s\">*</a>", u.Username)
} else if !u.Default {
td.Lights += fmt.Sprintf("<a href=\"/~%s\">+</a>", u.Username)
} else {
td.Lights += "."
}
}
2022-04-25 21:22:10 +00:00
t, err := template.New("blog").Parse(blogTmpl)
2021-08-06 07:31:25 +00:00
if err != nil {
2022-04-25 21:22:10 +00:00
return fmt.Errorf("failed to parse the blog template: %w", err)
2021-08-06 07:31:25 +00:00
}
out := bytes.Buffer{}
2022-04-25 22:20:11 +00:00
if err = t.Execute(&out, td); err != nil {
2022-04-25 21:22:10 +00:00
return fmt.Errorf("failed to render blog template: %w", err)
2021-08-06 07:31:25 +00:00
}
2022-04-25 21:22:10 +00:00
fmt.Println(out.String())
2021-08-06 07:31:25 +00:00
2022-04-25 21:22:10 +00:00
return nil
2021-08-06 07:31:25 +00:00
}
func stats() (*tildeData, error) {
sout := bytes.Buffer{}
cmd := exec.Command(statsPath)
cmd.Stdout = &sout
err := cmd.Run()
if err != nil {
return nil, err
}
2022-04-25 22:20:11 +00:00
var data tildeData
2021-08-06 07:31:25 +00:00
err = json.Unmarshal(sout.Bytes(), &data)
if err != nil {
return nil, err
}
return &data, nil
}
2021-08-06 03:18:46 +00:00
func main() {
2021-08-06 07:31:25 +00:00
err := _main()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
2021-08-06 03:18:46 +00:00
}