cpolis/cmd/data/rss.go

102 lines
1.9 KiB
Go
Raw Normal View History

2024-02-24 14:49:29 +01:00
package data
2024-02-18 12:41:49 +01:00
import (
"encoding/gob"
2024-02-18 12:41:49 +01:00
"fmt"
"os"
"sync"
2024-02-18 12:41:49 +01:00
"git.streifling.com/jason/rss"
2024-02-18 12:41:49 +01:00
)
type Channel struct {
addCh chan *rss.Item
setCh chan rss.Channel
getCh chan rss.Channel
channel rss.Channel
wg sync.WaitGroup
}
func initChannel() *Channel {
return &Channel{
addCh: make(chan *rss.Item),
setCh: make(chan rss.Channel),
getCh: make(chan rss.Channel),
}
2024-03-01 21:01:38 +01:00
}
func (c *Channel) start() {
c.wg.Done()
2024-03-01 21:01:38 +01:00
for {
select {
case item := <-c.addCh:
c.channel.Items = append(c.channel.Items, item)
case c.getCh <- c.channel:
case c.channel = <-c.setCh:
2024-03-01 21:01:38 +01:00
}
}
2024-02-18 12:41:49 +01:00
}
func NewChannel(title, link, desc string) *Channel {
channel := initChannel()
channel.channel = rss.Channel{
Title: title,
Link: link,
Description: desc,
2024-02-18 12:41:49 +01:00
}
channel.wg.Add(1)
go channel.start()
channel.wg.Wait()
return channel
2024-02-18 12:41:49 +01:00
}
func (c *Channel) Get() rss.Channel {
return <-c.getCh
}
2024-03-01 21:01:38 +01:00
func (f *Channel) Set(channel rss.Channel) {
f.setCh <- channel
}
func LoadChannel(filename string) (*Channel, error) {
file, err := os.Open(filename)
if err != nil {
2024-02-22 15:23:29 +01:00
return nil, fmt.Errorf("error opening file %v: %v", filename, err)
}
defer file.Close()
channel := initChannel()
channel.wg.Add(1)
go channel.start()
channel.wg.Wait()
tmpChannel := new(rss.Channel)
if err = gob.NewDecoder(file).Decode(tmpChannel); err != nil {
return nil, fmt.Errorf("error decoding channel from file %v: %v", filename, err)
}
channel.Set(*tmpChannel)
return channel, nil
}
func (c *Channel) Save(filename string) error {
2024-02-24 14:49:29 +01:00
file, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating file %v: %v", filename, err)
2024-02-18 12:41:49 +01:00
}
2024-02-24 14:49:29 +01:00
defer file.Close()
2024-02-18 12:41:49 +01:00
channel := c.Get()
if err = gob.NewEncoder(file).Encode(channel); err != nil {
2024-02-24 14:49:29 +01:00
return fmt.Errorf("error encoding file %v: %v", filename, err)
2024-02-18 12:41:49 +01:00
}
return nil
}
func (c *Channel) Add(i *rss.Item) {
c.addCh <- i
2024-03-01 21:01:38 +01:00
}