2017-11-20 00:10:04 -05: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.
|
|
|
|
|
|
|
|
package opml
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
|
|
|
"encoding/xml"
|
|
|
|
"log"
|
|
|
|
)
|
|
|
|
|
2017-11-20 17:35:11 -05:00
|
|
|
// Serialize returns a SubcriptionList in OPML format.
|
2017-11-20 00:10:04 -05:00
|
|
|
func Serialize(subscriptions SubcriptionList) string {
|
|
|
|
var b bytes.Buffer
|
|
|
|
writer := bufio.NewWriter(&b)
|
|
|
|
writer.WriteString(xml.Header)
|
|
|
|
|
2017-11-20 22:11:06 -05:00
|
|
|
feeds := new(opml)
|
|
|
|
feeds.Version = "2.0"
|
2017-11-20 00:10:04 -05:00
|
|
|
for categoryName, subs := range groupSubscriptionsByFeed(subscriptions) {
|
2017-11-20 22:11:06 -05:00
|
|
|
category := outline{Text: categoryName}
|
2017-11-20 00:10:04 -05:00
|
|
|
|
|
|
|
for _, subscription := range subs {
|
2017-11-20 22:11:06 -05:00
|
|
|
category.Outlines = append(category.Outlines, outline{
|
2017-11-20 00:10:04 -05:00
|
|
|
Title: subscription.Title,
|
|
|
|
Text: subscription.Title,
|
|
|
|
FeedURL: subscription.FeedURL,
|
|
|
|
SiteURL: subscription.SiteURL,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-11-20 22:11:06 -05:00
|
|
|
feeds.Outlines = append(feeds.Outlines, category)
|
2017-11-20 00:10:04 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
encoder := xml.NewEncoder(writer)
|
2017-11-20 17:35:11 -05:00
|
|
|
encoder.Indent(" ", " ")
|
2017-11-20 22:11:06 -05:00
|
|
|
if err := encoder.Encode(feeds); err != nil {
|
2017-11-20 00:10:04 -05:00
|
|
|
log.Println(err)
|
|
|
|
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
|
|
|
|
}
|