cpolis/cmd/data/rss.go

102 lines
1.7 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
"github.com/gorilla/feeds"
)
type Feed struct {
addCh chan *feeds.Item
setCh chan feeds.Feed
getCh chan feeds.Feed
feed feeds.Feed
wg sync.WaitGroup
}
2024-03-05 16:38:18 +01:00
func initFeed() *Feed {
return &Feed{
addCh: make(chan *feeds.Item),
setCh: make(chan feeds.Feed),
getCh: make(chan feeds.Feed),
}
2024-03-01 21:01:38 +01:00
}
func (f *Feed) start() {
f.wg.Done()
2024-03-01 21:01:38 +01:00
for {
select {
case item := <-f.addCh:
f.feed.Items = append(f.feed.Items, item)
case f.getCh <- f.feed:
case f.feed = <-f.setCh:
2024-03-01 21:01:38 +01:00
}
}
2024-02-18 12:41:49 +01:00
}
func NewFeed(title, link, desc string) *Feed {
2024-03-05 16:38:18 +01:00
feed := initFeed()
feed.feed = feeds.Feed{
Title: title,
Link: &feeds.Link{Href: link},
Description: desc,
2024-02-18 12:41:49 +01:00
}
feed.wg.Add(1)
2024-03-01 21:01:38 +01:00
go feed.start()
feed.wg.Wait()
2024-03-01 21:01:38 +01:00
return feed
2024-02-18 12:41:49 +01:00
}
func (f *Feed) Get() feeds.Feed {
return <-f.getCh
}
2024-03-01 21:01:38 +01:00
func (f *Feed) Set(feed feeds.Feed) {
f.setCh <- feed
}
func OpenFeed(filename string) (*Feed, 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()
2024-03-05 16:38:18 +01:00
feed := initFeed()
feed.wg.Add(1)
go feed.start()
feed.wg.Wait()
2024-03-01 21:01:38 +01:00
tmpFeed := new(feeds.Feed)
2024-03-05 16:38:18 +01:00
if err = gob.NewDecoder(file).Decode(tmpFeed); err != nil {
2024-02-22 15:23:29 +01:00
return nil, fmt.Errorf("error decoding file %v: %v", filename, err)
}
feed.Set(*tmpFeed)
return feed, nil
}
func (f *Feed) 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
feed := f.Get()
2024-03-05 16:38:18 +01:00
if err = gob.NewEncoder(file).Encode(feed); 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 (f *Feed) Add(i *feeds.Item) {
2024-03-01 21:01:38 +01:00
f.addCh <- i
}