Skip to content

Instantly share code, notes, and snippets.

@MoriTanosuke
Created November 13, 2024 10:19
Show Gist options
  • Save MoriTanosuke/d9510e948afed9e215b4eeade873bbb1 to your computer and use it in GitHub Desktop.
Save MoriTanosuke/d9510e948afed9e215b4eeade873bbb1 to your computer and use it in GitHub Desktop.
Simple go application to build a RSS feed from a mastodon status URL
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"log"
"math"
"net/http"
"os"
"time"
)
type Status struct {
Descendants []struct {
Account struct {
Username string
DisplayName string \`json:"display_name"\`
}
CreatedAt time.Time \`json:"created_at"\`
Content string
Url string
}
}
type Item struct {
PubDate time.Time \`xml:"pubDate"\`
Title string \`xml:"title"\`
Description string \`xml:"description"\`
Link string \`xml:"link"\`
}
type Channel struct {
Title string \`xml:"title"\`
Link string \`xml:"link"\`
Item []Item \`xml:"item"\`
}
type Rss struct {
XMLName xml.Name \`xml:"rss"\`
Channel Channel \`xml:"channel"\`
}
func main() {
// application to generate a RSS feed from mastodon status URL like
//
// use like this in a crontab: replyfetcher https://social.tchncs.de/api/v1/statuses/113474228564749371/context > feed.rss
if len(os.Args) < 2 {
log.Fatalf("Usage: %s <url to status>", os.Args[0])
}
url := os.Args[1]
resp, err := http.Get(url)
if err != nil || resp.StatusCode >= 400 {
log.Fatalf("Can not get status: %v %v", err, resp.Status)
}
var content Status
err = json.NewDecoder(resp.Body).Decode(&content)
if err != nil {
log.Fatalf("Can not decode json: %v", err)
}
feed := Rss{
Channel: Channel{
Title: url,
Link: url,
},
}
for _, descendant := range content.Descendants {
user := descendant.Account.Username
if descendant.Account.DisplayName != "" {
user = descendant.Account.DisplayName
}
maxlength := int(math.Min(100, float64(len(descendant.Content))))
title := descendant.Content[0:maxlength]
feed.Channel.Item = append(feed.Channel.Item, Item{
PubDate: descendant.CreatedAt,
Title: fmt.Sprintf("%s: %s", user, title),
Description: descendant.Content,
Link: descendant.Url,
})
}
xmlContent, _ := xml.MarshalIndent(feed, "", " ")
fmt.Printf("<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?>\\n%s", xmlContent)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment