wisski-cloud-distillery/internal/component/home/public.go
2022-11-16 13:07:07 +01:00

90 lines
2 KiB
Go

package home
import (
"bytes"
"context"
"text/template"
"time"
_ "embed"
"github.com/FAU-CDI/wisski-distillery/internal/component/instances"
"github.com/FAU-CDI/wisski-distillery/pkg/timex"
"github.com/tkw1536/goprogram/stream"
"golang.org/x/sync/errgroup"
)
func (home *Home) updateInstances(ctx context.Context, io stream.IOStream) {
timex.SetInterval(ctx, home.RefreshInterval, func(t time.Time) {
io.Printf("[%s]: reloading instance list", t.String())
names, _ := home.instanceMap()
home.instanceNames.Set(names)
})
}
func (home *Home) instanceMap() (map[string]struct{}, error) {
wissKIs, err := home.Instances.All()
if err != nil {
return nil, err
}
names := make(map[string]struct{}, len(wissKIs))
for _, w := range wissKIs {
names[w.Slug] = struct{}{}
}
return names, nil
}
func (home *Home) updateRender(ctx context.Context, io stream.IOStream) {
timex.SetInterval(ctx, home.RefreshInterval, func(t time.Time) {
io.Printf("[%s]: reloading home render", t.String())
bytes, _ := home.homeRender()
home.homeBytes.Set(bytes)
})
}
//go:embed "home.html"
var homeHTMLStr string
var homeTemplate = template.Must(template.New("home.html").Parse(homeHTMLStr))
func (home *Home) homeRender() ([]byte, error) {
var context HomeContext
// setup a couple of static things
context.Time = time.Now().UTC()
context.SelfRedirect = home.Config.SelfRedirect.String()
// find all the WissKIs
wissKIs, err := home.Instances.All()
if err != nil {
return nil, err
}
context.Instances = make([]instances.WissKIInfo, len(wissKIs))
// determine their infos
var eg errgroup.Group
for i, instance := range wissKIs {
i := i
wissKI := instance
eg.Go(func() (err error) {
context.Instances[i], err = wissKI.Info(true)
return
})
}
eg.Wait()
// render the template
var buffer bytes.Buffer
homeTemplate.Execute(&buffer, context)
return buffer.Bytes(), nil
}
type HomeContext struct {
Instances []instances.WissKIInfo
Time time.Time
SelfRedirect string
}