aboutsummaryrefslogtreecommitdiffhomepage
path: root/reader/opml/serializer.go
blob: c094f4c4f167b01225c4992937f6fe6f896012b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// 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 "miniflux.app/reader/opml"

import (
	"bufio"
	"bytes"
	"encoding/xml"

	"miniflux.app/logger"
)

// Serialize returns a SubcriptionList in OPML format.
func Serialize(subscriptions SubcriptionList) string {
	var b bytes.Buffer
	writer := bufio.NewWriter(&b)
	writer.WriteString(xml.Header)

	feeds := new(opml)
	feeds.Version = "2.0"
	for categoryName, subs := range groupSubscriptionsByFeed(subscriptions) {
		category := outline{Text: categoryName}

		for _, subscription := range subs {
			category.Outlines = append(category.Outlines, outline{
				Title:   subscription.Title,
				Text:    subscription.Title,
				FeedURL: subscription.FeedURL,
				SiteURL: subscription.SiteURL,
			})
		}

		feeds.Outlines = append(feeds.Outlines, category)
	}

	encoder := xml.NewEncoder(writer)
	encoder.Indent("    ", "    ")
	if err := encoder.Encode(feeds); err != nil {
		logger.Error("[OPML:Serialize] %v", 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
}