format.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package parser // import "miniflux.app/v2/internal/reader/parser"
  4. import (
  5. "bytes"
  6. "encoding/xml"
  7. "io"
  8. rxml "miniflux.app/v2/internal/reader/xml"
  9. )
  10. // List of feed formats.
  11. const (
  12. FormatRDF = "rdf"
  13. FormatRSS = "rss"
  14. FormatAtom = "atom"
  15. FormatJSON = "json"
  16. FormatUnknown = "unknown"
  17. )
  18. // DetectFeedFormat tries to guess the feed format from input data.
  19. func DetectFeedFormat(r io.ReadSeeker) (string, string) {
  20. data := make([]byte, 512)
  21. r.Read(data)
  22. if bytes.HasPrefix(bytes.TrimSpace(data), []byte("{")) {
  23. return FormatJSON, ""
  24. }
  25. r.Seek(0, io.SeekStart)
  26. decoder := rxml.NewXMLDecoder(r)
  27. for {
  28. token, _ := decoder.Token()
  29. if token == nil {
  30. break
  31. }
  32. if element, ok := token.(xml.StartElement); ok {
  33. switch element.Name.Local {
  34. case "rss":
  35. return FormatRSS, ""
  36. case "feed":
  37. for _, attr := range element.Attr {
  38. if attr.Name.Local == "version" && attr.Value == "0.3" {
  39. return FormatAtom, "0.3"
  40. }
  41. }
  42. return FormatAtom, "1.0"
  43. case "RDF":
  44. return FormatRDF, ""
  45. }
  46. }
  47. }
  48. return FormatUnknown, ""
  49. }