miniflux/reader/opml/serializer.go

70 lines
1.7 KiB
Go
Raw Normal View History

2017-11-20 06:10:04 +01:00
// Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
2018-08-25 06:51:50 +02:00
package opml // import "miniflux.app/reader/opml"
2017-11-20 06:10:04 +01:00
import (
"bufio"
"bytes"
"encoding/xml"
"sort"
2017-12-16 03:55:57 +01:00
2018-08-25 06:51:50 +02:00
"miniflux.app/logger"
2017-11-20 06:10:04 +01:00
)
2017-11-20 23:35:11 +01:00
// Serialize returns a SubcriptionList in OPML format.
2017-11-20 06:10:04 +01:00
func Serialize(subscriptions SubcriptionList) string {
var b bytes.Buffer
writer := bufio.NewWriter(&b)
writer.WriteString(xml.Header)
feeds := normalizeFeeds(subscriptions)
2017-11-20 06:10:04 +01:00
encoder := xml.NewEncoder(writer)
2017-11-20 23:35:11 +01:00
encoder.Indent(" ", " ")
if err := encoder.Encode(feeds); err != nil {
2017-12-16 03:55:57 +01:00
logger.Error("[OPML:Serialize] %v", err)
2017-11-20 06:10:04 +01:00
return ""
}
return b.String()
}
func groupSubscriptionsByFeed(subscriptions SubcriptionList) map[string]SubcriptionList {
groups := make(map[string]SubcriptionList)
for _, subscription := range subscriptions {
groups[subscription.CategoryName] = append(groups[subscription.CategoryName], subscription)
}
return groups
}
func normalizeFeeds(subscriptions SubcriptionList) *opml {
feeds := new(opml)
feeds.Version = "2.0"
groupedSubs := groupSubscriptionsByFeed(subscriptions)
var categories []string
for k := range groupedSubs {
categories = append(categories, k)
}
sort.Strings(categories)
for _, categoryName := range categories {
category := outline{Text: categoryName}
for _, subscription := range groupedSubs[categoryName] {
category.Outlines = append(category.Outlines, outline{
Title: subscription.Title,
Text: subscription.Title,
FeedURL: subscription.FeedURL,
SiteURL: subscription.SiteURL,
})
}
feeds.Outlines = append(feeds.Outlines, category)
}
return feeds
}