cpolis/cmd/data/rss.go

94 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"
2024-02-18 12:41:49 +01:00
"github.com/gorilla/feeds"
)
type Feed struct {
2024-03-01 21:01:38 +01:00
addCh chan *feeds.Item
openCh chan feeds.Feed
saveCh chan feeds.Feed
showCh chan feeds.Feed
feed feeds.Feed
}
func (f *Feed) start() {
for {
select {
case item := <-f.addCh:
f.feed.Items = append(f.feed.Items, item)
case f.saveCh <- f.feed:
case tmpFeed := <-f.openCh:
f.feed = tmpFeed
case f.showCh <- f.feed:
}
}
2024-02-18 12:41:49 +01:00
}
func NewFeed(title, link, desc string) *Feed {
2024-03-01 21:01:38 +01:00
feed := &Feed{
addCh: make(chan *feeds.Item),
openCh: make(chan feeds.Feed),
saveCh: make(chan feeds.Feed),
showCh: make(chan feeds.Feed),
feed: feeds.Feed{
2024-02-18 12:41:49 +01:00
Title: title,
Link: &feeds.Link{Href: link},
Description: desc,
},
}
2024-03-01 21:01:38 +01:00
go feed.start()
return feed
2024-02-18 12:41:49 +01:00
}
func OpenFeed(filename string) (*Feed, error) {
2024-03-01 21:01:38 +01:00
feed := new(Feed)
go feed.start()
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()
decoder := gob.NewDecoder(file)
2024-03-01 21:01:38 +01:00
tmpFeed := new(feeds.Feed)
err = decoder.Decode(tmpFeed)
if err != nil {
2024-02-22 15:23:29 +01:00
return nil, fmt.Errorf("error decoding file %v: %v", filename, err)
}
2024-03-01 21:01:38 +01:00
feed.openCh <- *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
2024-02-24 14:49:29 +01:00
encoder := gob.NewEncoder(file)
2024-03-01 21:01:38 +01:00
feed := <-f.saveCh
err = encoder.Encode(feed)
2024-02-18 12:41:49 +01:00
if 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
}
func (f *Feed) Show() feeds.Feed {
return <-f.showCh
}