intake/cmd/feed.go

102 lines
2.1 KiB
Go
Raw Normal View History

2025-01-17 15:05:57 +00:00
package cmd
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"github.com/Jaculabilis/intake/core"
"github.com/spf13/cobra"
)
var feedCmd = &cobra.Command{
Use: "feed",
Short: "Print item feeds",
Long: `Display the intake item feed in various formats.
The default format is "headlines".
Available formats:
headlines Only item titles
json Full item JSON
short Item source and id
`,
Run: func(cmd *cobra.Command, args []string) {
feed()
},
}
var feedFormat string
var feedSource string
var feedChannel string
func init() {
rootCmd.AddCommand(feedCmd)
feedCmd.Flags().StringVarP(&feedFormat, "format", "f", "headlines", "Feed format")
feedCmd.Flags().StringVarP(&feedSource, "source", "s", "", "Limit to items from source")
feedCmd.Flags().StringVarP(&feedChannel, "channel", "c", "", "Limit to items from channel")
feedCmd.MarkFlagsMutuallyExclusive("source", "channel")
}
func feed() {
var formatter func(core.Item)
switch feedFormat {
case "headlines":
formatter = formatHeadline
case "json":
formatter = formatJson
case "short":
formatter = formatShort
default:
log.Fatalf("error: invalid format %s", feedFormat)
}
db, err := sql.Open("sqlite3", getDbPath())
if err != nil {
log.Fatalf("error: failed to open %s", dbPath)
}
core.InitDatabase(db)
core.MigrateDatabase(db)
var items []core.Item
if feedSource != "" {
items, err = core.GetActiveItemsForSource(db, feedSource)
if err != nil {
log.Fatalf("error: failed to fetch items from %s", feedSource)
}
} else if feedChannel != "" {
log.Fatal("error: unimplemented")
} else {
items, err = core.GetAllActiveItems(db)
if err != nil {
log.Fatal("error: failed to fetch items")
}
}
for _, item := range items {
formatter(item)
}
}
func formatHeadline(item core.Item) {
title := item.Title
if title == "" {
title = item.Id
}
fmt.Println(title)
}
func formatJson(item core.Item) {
data, err := json.Marshal(item)
if err != nil {
log.Fatalf("error: failed to serialize %s/%s: %v", item.Source, item.Id, err)
}
fmt.Println(string(data))
}
func formatShort(item core.Item) {
fmt.Printf("%s/%s\n", item.Source, item.Id)
}