serializer.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package opml // import "miniflux.app/reader/opml"
  5. import (
  6. "bufio"
  7. "bytes"
  8. "encoding/xml"
  9. "miniflux.app/logger"
  10. )
  11. // Serialize returns a SubcriptionList in OPML format.
  12. func Serialize(subscriptions SubcriptionList) string {
  13. var b bytes.Buffer
  14. writer := bufio.NewWriter(&b)
  15. writer.WriteString(xml.Header)
  16. feeds := new(opml)
  17. feeds.Version = "2.0"
  18. for categoryName, subs := range groupSubscriptionsByFeed(subscriptions) {
  19. category := outline{Text: categoryName}
  20. for _, subscription := range subs {
  21. category.Outlines = append(category.Outlines, outline{
  22. Title: subscription.Title,
  23. Text: subscription.Title,
  24. FeedURL: subscription.FeedURL,
  25. SiteURL: subscription.SiteURL,
  26. })
  27. }
  28. feeds.Outlines = append(feeds.Outlines, category)
  29. }
  30. encoder := xml.NewEncoder(writer)
  31. encoder.Indent(" ", " ")
  32. if err := encoder.Encode(feeds); err != nil {
  33. logger.Error("[OPML:Serialize] %v", err)
  34. return ""
  35. }
  36. return b.String()
  37. }
  38. func groupSubscriptionsByFeed(subscriptions SubcriptionList) map[string]SubcriptionList {
  39. groups := make(map[string]SubcriptionList)
  40. for _, subscription := range subscriptions {
  41. groups[subscription.CategoryName] = append(groups[subscription.CategoryName], subscription)
  42. }
  43. return groups
  44. }