1
0
mirror of https://github.com/mrusme/neonmodem.git synced 2024-06-16 06:25:23 +00:00
neonmodem/aggregator/aggregator.go

110 lines
2.3 KiB
Go
Raw Permalink Normal View History

2022-12-30 08:22:54 +00:00
package aggregator
import (
2022-12-31 23:55:02 +00:00
"encoding/json"
"os"
2022-12-30 08:22:54 +00:00
"sort"
2023-01-05 16:43:52 +00:00
"strings"
2022-12-30 08:22:54 +00:00
2023-01-07 00:46:41 +00:00
"github.com/mrusme/neonmodem/models/forum"
"github.com/mrusme/neonmodem/models/post"
"github.com/mrusme/neonmodem/models/reply"
"github.com/mrusme/neonmodem/ui/ctx"
2022-12-30 08:22:54 +00:00
)
type Aggregator struct {
ctx *ctx.Ctx
}
func New(c *ctx.Ctx) (*Aggregator, error) {
a := new(Aggregator)
a.ctx = c
return a, nil
}
2023-01-05 16:43:52 +00:00
func (a *Aggregator) ListForums() ([]forum.Forum, []error) {
var errs []error = make([]error, len(a.ctx.Systems))
var forums []forum.Forum
for idx, sys := range a.ctx.Systems {
if curSysIDX := a.ctx.GetCurrentSystem(); curSysIDX != -1 {
if idx != curSysIDX {
continue
}
}
sysForums, err := (*sys).ListForums()
if err != nil {
errs[idx] = err
continue
}
forums = append(forums, sysForums...)
}
sort.SliceStable(forums, func(i, j int) bool {
return strings.Compare(forums[i].Title(), forums[j].Title()) == -1
2023-01-05 16:43:52 +00:00
})
return forums, errs
}
2022-12-30 08:22:54 +00:00
func (a *Aggregator) ListPosts() ([]post.Post, []error) {
var errs []error = make([]error, len(a.ctx.Systems))
var posts []post.Post
2022-12-31 23:55:02 +00:00
// TODO: Clean up implementation
if os.Getenv("NEONMODEM_TEST") == "true" {
2022-12-31 23:55:02 +00:00
jsonPosts, err := os.ReadFile("posts.db")
if err == nil {
err = json.Unmarshal(jsonPosts, &posts)
if err == nil {
return posts, nil
}
}
}
2022-12-30 08:22:54 +00:00
for idx, sys := range a.ctx.Systems {
2023-01-05 16:43:52 +00:00
if curSysIDX := a.ctx.GetCurrentSystem(); curSysIDX != -1 {
if idx != curSysIDX {
continue
}
}
sysPosts, err := (*sys).ListPosts(a.ctx.GetCurrentForum().ID)
2022-12-30 08:22:54 +00:00
if err != nil {
2023-01-06 02:44:34 +00:00
a.ctx.Logger.Errorf("aggregator error: %v\n", err)
2022-12-30 08:22:54 +00:00
errs[idx] = err
continue
}
posts = append(posts, sysPosts...)
}
sort.SliceStable(posts, func(i, j int) bool {
return posts[i].CreatedAt.After(posts[j].CreatedAt)
})
2022-12-31 23:55:02 +00:00
// TODO: Clean up implementation
if os.Getenv("NEONMODEM_TEST") == "true" {
jsonPosts, err := json.Marshal(posts)
if err == nil {
os.WriteFile("posts.db", jsonPosts, 0600)
}
2022-12-31 23:55:02 +00:00
}
2022-12-30 08:22:54 +00:00
return posts, errs
}
func (a *Aggregator) LoadPost(p *post.Post) error {
return (*a.ctx.Systems[p.SysIDX]).LoadPost(p)
}
func (a *Aggregator) CreatePost(p *post.Post) error {
return (*a.ctx.Systems[p.SysIDX]).CreatePost(p)
}
func (a *Aggregator) CreateReply(r *reply.Reply) error {
return (*a.ctx.Systems[r.SysIDX]).CreateReply(r)
}