aboutsummaryrefslogtreecommitdiff
path: root/internal/reader/parser/format.go
blob: b0a7c2e36c04b12d7af003739c6f8fc06ae7cc01 (plain) (blame)
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
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package parser // import "miniflux.app/v2/internal/reader/parser"

import (
	"bytes"
	"encoding/xml"
	"io"

	rxml "miniflux.app/v2/internal/reader/xml"
)

// List of feed formats.
const (
	FormatRDF     = "rdf"
	FormatRSS     = "rss"
	FormatAtom    = "atom"
	FormatJSON    = "json"
	FormatUnknown = "unknown"
)

// DetectFeedFormat tries to guess the feed format from input data.
func DetectFeedFormat(r io.ReadSeeker) string {
	data := make([]byte, 512)
	r.Read(data)

	if bytes.HasPrefix(bytes.TrimSpace(data), []byte("{")) {
		return FormatJSON
	}

	r.Seek(0, io.SeekStart)
	decoder := rxml.NewXMLDecoder(r)

	for {
		token, _ := decoder.Token()
		if token == nil {
			break
		}

		if element, ok := token.(xml.StartElement); ok {
			switch element.Name.Local {
			case "rss":
				return FormatRSS
			case "feed":
				return FormatAtom
			case "RDF":
				return FormatRDF
			}
		}
	}

	return FormatUnknown
}