format.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. "encoding/xml"
  6. "io"
  7. "unicode"
  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. const maxTokensToConsider = uint(50)
  19. // DetectFeedFormat tries to guess the feed format from input data.
  20. func DetectFeedFormat(r io.ReadSeeker) (string, string) {
  21. r.Seek(0, io.SeekStart)
  22. defer r.Seek(0, io.SeekStart)
  23. if isJSON, err := detectJSONFormat(r); err == nil && isJSON {
  24. return FormatJSON, ""
  25. }
  26. r.Seek(0, io.SeekStart)
  27. decoder := rxml.NewXMLDecoder(r)
  28. processedTokens := uint(0)
  29. for {
  30. token, _ := decoder.Token()
  31. if token == nil || processedTokens == maxTokensToConsider {
  32. break
  33. }
  34. processedTokens += 1
  35. if element, ok := token.(xml.StartElement); ok {
  36. switch element.Name.Local {
  37. case "rss":
  38. return FormatRSS, ""
  39. case "feed":
  40. for _, attr := range element.Attr {
  41. if attr.Name.Local == "version" && attr.Value == "0.3" {
  42. return FormatAtom, "0.3"
  43. }
  44. }
  45. return FormatAtom, "1.0"
  46. case "RDF":
  47. return FormatRDF, ""
  48. }
  49. }
  50. }
  51. return FormatUnknown, ""
  52. }
  53. // detectJSONFormat checks if the reader contains JSON by reading until it finds
  54. // the first non-whitespace character or reaches EOF/error.
  55. func detectJSONFormat(r io.ReadSeeker) (bool, error) {
  56. const bufferSize = 32
  57. buffer := make([]byte, bufferSize)
  58. for {
  59. n, err := r.Read(buffer)
  60. if n == 0 {
  61. if err == io.EOF {
  62. return false, nil // No non-whitespace content found
  63. }
  64. return false, err
  65. }
  66. if len(buffer) < n {
  67. panic("unreachable") // bounds check hint to compiler
  68. }
  69. // Check each byte in the buffer
  70. for i := range n {
  71. ch := buffer[i]
  72. // Skip whitespace characters (space, tab, newline, carriage return, etc.)
  73. if unicode.IsSpace(rune(ch)) {
  74. continue
  75. }
  76. // First non-whitespace character determines if it's JSON
  77. return ch == '{', nil
  78. }
  79. // If we've read less than bufferSize, we've reached EOF
  80. if n < bufferSize {
  81. return false, nil
  82. }
  83. }
  84. }