ribbit/helper_xkcd.go

75 lines
1.8 KiB
Go

package main
import (
"errors"
"fmt"
"net/http"
"time"
"github.com/PuerkitoBio/goquery"
)
func downloadXKCDList() []Comic {
var ret []Comic
ret = append(ret, *NewComic("xkcd", "XKCD", "Randall Munroe", "xkcd"))
return ret
}
func getXKCDRssItem(slug string) (string, error) {
desc, err := getXKCDFeedDesc(time.Now())
if err != nil {
return "", err
}
comic, err := m.GetComic(SRC_XKCD, slug)
if err != nil {
return "", err
}
desc = "<![CDATA[" + desc + "]]>"
ret := " <item>\n"
ret += " <title>" + comic.Name + "</title>\n"
ret += " <pubDate>" + comic.LastUpdate.Format(time.RFC1123Z) + "</pubDate>\n"
ret += " <guid>xkcd;" + slug + ";" + comic.LastUpdate.Format(time.RFC1123Z) + "</guid>\n"
ret += " <link>" + getXKCDComicUrl(time.Now()) + "</link>\n"
ret += " <description>" + desc + "</description>\n"
ret += " </item>\n"
return ret, nil
}
func getXKCDComicUrl(date time.Time) string {
// TODO: Actually make this work correctly
// Get the previous comic number
// and find the next one
return fmt.Sprintf(
"http://xkcd.com/",
)
}
func getXKCDFeedDesc(date time.Time) (string, error) {
res, err := http.Get(getXKCDComicUrl(date))
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return "", errors.New(fmt.Sprintf("Status code error: %d %s", res.StatusCode, res.Status))
}
// Load the HTML document
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
return "", err
}
// Find the Picture
sel := doc.Find("div#comic>img")
src, exists := sel.Attr("src")
if !exists {
return "", errors.New("Couldn't find image source")
}
src = "https:" + src
title, exists := sel.Attr("title")
if !exists {
title = ""
}
return "<img src=\"" + src + "\" /><p>" + title + "</p>", nil
}