pogo/generate_rss.go

127 lines
2.8 KiB
Go
Raw Normal View History

/* generate_rss.go
2017-09-21 20:10:16 +01:00
*
* This file contains functions for monitoring for file changes and
* regenerating the RSS feed accordingly, pulling in shownote files
* and configuration parameters
2017-09-21 20:10:16 +01:00
*/
package main
import (
"fmt"
"io/ioutil"
"log"
"strings"
"time"
"github.com/fsnotify/fsnotify"
"github.com/gmemstr/feeds"
)
// Watch folder for changes, called from webserver.go
func watch() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
2017-09-19 20:28:59 +01:00
// Call func asynchronously
go func() {
for {
select {
case event := <-watcher.Events:
2017-09-11 18:10:35 +01:00
// log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
generate_rss()
}
case err := <-watcher.Errors:
log.Println("error:", err)
}
}
}()
err = watcher.Add("podcasts/")
if err != nil {
log.Fatal(err)
}
err = watcher.Add("assets/config/config.json")
if err != nil {
log.Fatal(err)
}
<-done
}
// Called when a file has been created / changed, uses gorilla feeds
// fork to add items to feed object
func generate_rss() {
config,err := ReadConfig()
if err != nil {
panic(err)
}
now := time.Now()
files, err := ioutil.ReadDir("podcasts")
if err != nil {
log.Fatal(err)
}
podcasturl := config.PodcastUrl
feed := &feeds.Feed{
Title: config.Name,
Link: &feeds.Link{Href: podcasturl},
Description: config.Description,
Author: &feeds.Author{Name: config.Host, Email: config.Email},
Created: now,
Image: &feeds.Image{Url: config.Image},
}
for _, file := range files {
if strings.Contains(file.Name(), ".mp3") {
s := strings.Split(file.Name(), "_")
t := strings.Split(s[1], ".")
title := t[0]
2017-09-21 20:10:16 +01:00
description, err := ioutil.ReadFile("podcasts/" + strings.Replace(file.Name(), ".mp3", "_SHOWNOTES.md", 2))
if err != nil {
2017-09-21 20:10:16 +01:00
log.Fatal(err)
}
date, err := time.Parse("2006-01-02", s[0])
if err != nil {
log.Fatal(err)
}
size := fmt.Sprintf("%d", file.Size())
link := podcasturl + "/download/" + file.Name()
2017-09-21 20:10:16 +01:00
feed.Add(
&feeds.Item{
Title: title,
Link: &feeds.Link{Href: link, Length: size, Type: "audio/mpeg"},
Enclosure: &feeds.Enclosure{Url: link, Length: size, Type: "audio/mpeg"},
Description: string(description),
Author: &feeds.Author{Name: config.Host, Email: config.Email},
Created: date,
},
)
}
}
// Translate the feed to both RSS and JSON,
// RSS for readers and JSON for frontend (& API I guess)
rss, err := feed.ToRss()
if err != nil {
log.Fatal(err)
}
json, err := feed.ToJSON()
if err != nil {
log.Fatal(err)
}
// fmt.Println(rss)
2017-09-21 20:10:16 +01:00
// Write to files as neccesary
rss_byte := []byte(rss)
ioutil.WriteFile("assets/web/feed.rss", rss_byte, 0644)
2017-09-21 20:10:16 +01:00
json_byte := []byte(json)
ioutil.WriteFile("assets/web/feed.json", json_byte, 0644)
}