380 lines
10 KiB
Go
380 lines
10 KiB
Go
package feeds
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/csv"
|
|
"encoding/xml"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
)
|
|
|
|
// defaultMaxParseRows caps CSV/XML product rows per sync. Parse is streaming
|
|
// (one row at a time); the bound limits sync duration and DB write volume for
|
|
// oversized catalogs. Exceeding returns parseTooManyRows() with the numeric limit.
|
|
const defaultMaxParseRows = 1_000_000
|
|
|
|
// maxParseRows is the active row cap. Mutable for tests.
|
|
var maxParseRows = defaultMaxParseRows
|
|
|
|
// errParseTooManyRows is the sentinel for ClientError / errors.Is checks.
|
|
var errParseTooManyRows = errors.New("feed exceeds max row limit")
|
|
|
|
// parseTooManyRows returns errParseTooManyRows with the active row limit for clients.
|
|
func parseTooManyRows() error {
|
|
return fmt.Errorf("%w (%d)", errParseTooManyRows, maxParseRows)
|
|
}
|
|
|
|
// feedRow is a normalized flat record from CSV or XML.
|
|
type feedRow map[string]string
|
|
|
|
func detectFeedFormat(feedType, contentType, urlHint string, sample []byte) string {
|
|
ft := strings.ToLower(strings.TrimSpace(feedType))
|
|
// Binary workbooks win over the declared type: local uploads default to text/csv.
|
|
if ft == "excel" || isExcelSample(sample) {
|
|
return "excel"
|
|
}
|
|
if ft == "csv" || ft == "xml" || ft == "json" {
|
|
return ft
|
|
}
|
|
ct := strings.ToLower(contentType)
|
|
u := strings.ToLower(urlHint)
|
|
switch {
|
|
case isExcelContentType(ct) || isExcelName(u):
|
|
return "excel"
|
|
case strings.Contains(ct, "json") || strings.Contains(u, ".json") || strings.Contains(u, "format=json"):
|
|
return "json"
|
|
case strings.Contains(ct, "csv") || strings.HasSuffix(u, ".csv"):
|
|
return "csv"
|
|
case strings.Contains(ct, "xml") || strings.HasSuffix(u, ".xml"):
|
|
return "xml"
|
|
}
|
|
trimmed := bytes.TrimSpace(sample)
|
|
if len(trimmed) > 0 && (trimmed[0] == '{' || trimmed[0] == '[') {
|
|
return "json"
|
|
}
|
|
if len(trimmed) > 0 && trimmed[0] == '<' {
|
|
return "xml"
|
|
}
|
|
return "csv"
|
|
}
|
|
|
|
// parseCSV streams rows via callback to avoid holding the full matrix when possible.
|
|
// The CSV reader still tokenizes; we only keep one row at a time in the callback path.
|
|
func parseCSV(r io.Reader, onRow func(feedRow) error) (int, error) {
|
|
cr := csv.NewReader(r)
|
|
cr.ReuseRecord = true
|
|
cr.LazyQuotes = true
|
|
cr.TrimLeadingSpace = true
|
|
cr.FieldsPerRecord = -1
|
|
|
|
header, err := cr.Read()
|
|
if err != nil {
|
|
return 0, fmt.Errorf("csv header: %w", err)
|
|
}
|
|
cols := make([]string, len(header))
|
|
for i, h := range header {
|
|
cols[i] = strings.TrimSpace(strings.TrimPrefix(h, "\uFEFF"))
|
|
}
|
|
count := 0
|
|
for {
|
|
rec, err := cr.Read()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return count, fmt.Errorf("csv row %d: %w", count+1, err)
|
|
}
|
|
count++
|
|
if count > maxParseRows {
|
|
return count, parseTooManyRows()
|
|
}
|
|
row := make(feedRow, len(cols))
|
|
for i, col := range cols {
|
|
if col == "" {
|
|
continue
|
|
}
|
|
if i < len(rec) {
|
|
row[col] = rec[i]
|
|
} else {
|
|
row[col] = ""
|
|
}
|
|
}
|
|
expandSpecificationFields(row)
|
|
if err := onRow(row); err != nil {
|
|
return count, err
|
|
}
|
|
}
|
|
return count, nil
|
|
}
|
|
|
|
// parseXMLItems streams element-local text maps for repeating item tags.
|
|
// When itemLocal is empty and r is seekable, a small prefix is sniffed then rewound.
|
|
func parseXMLItems(r io.Reader, itemLocal string, onRow func(feedRow) error) (int, error) {
|
|
itemLocal = strings.TrimSpace(itemLocal)
|
|
if itemLocal == "" {
|
|
var err error
|
|
itemLocal, r, err = resolveXMLItemLocal(r)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
}
|
|
dec := xml.NewDecoder(r)
|
|
dec.Strict = false
|
|
count := 0
|
|
for {
|
|
tok, err := dec.Token()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return count, fmt.Errorf("xml: %w", err)
|
|
}
|
|
se, ok := tok.(xml.StartElement)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if !localNameEquals(se.Name, itemLocal) {
|
|
continue
|
|
}
|
|
row, err := readXMLElementMap(dec, se)
|
|
if err != nil {
|
|
return count, err
|
|
}
|
|
expandSpecificationFields(row)
|
|
count++
|
|
if count > maxParseRows {
|
|
return count, parseTooManyRows()
|
|
}
|
|
if err := onRow(row); err != nil {
|
|
return count, err
|
|
}
|
|
}
|
|
return count, nil
|
|
}
|
|
|
|
const xmlItemGuessBytes = 64 << 10
|
|
|
|
func resolveXMLItemLocal(r io.Reader) (string, io.Reader, error) {
|
|
if rs, ok := r.(io.ReadSeeker); ok {
|
|
sample := make([]byte, xmlItemGuessBytes)
|
|
n, err := io.ReadFull(rs, sample)
|
|
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
|
|
return "", nil, err
|
|
}
|
|
sample = sample[:n]
|
|
local := guessXMLItemLocal(sample)
|
|
if _, err := rs.Seek(0, io.SeekStart); err != nil {
|
|
return "", nil, err
|
|
}
|
|
return local, rs, nil
|
|
}
|
|
sample, err := io.ReadAll(io.LimitReader(r, xmlItemGuessBytes))
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
local := guessXMLItemLocal(sample)
|
|
return local, io.MultiReader(bytes.NewReader(sample), r), nil
|
|
}
|
|
|
|
func guessXMLItemLocal(data []byte) string {
|
|
sample := string(data)
|
|
if len(sample) > xmlItemGuessBytes {
|
|
sample = sample[:xmlItemGuessBytes]
|
|
}
|
|
lower := strings.ToLower(sample)
|
|
for _, cand := range []string{"shopitem", "item", "entry", "offer", "row", "product"} {
|
|
if strings.Contains(lower, "<"+cand) || strings.Contains(lower, ":"+cand) {
|
|
return cand
|
|
}
|
|
}
|
|
if p := guessRepeatedXMLItemPath([]byte(sample)); p != "" {
|
|
return leafName(p)
|
|
}
|
|
return "item"
|
|
}
|
|
|
|
// guessRepeatedXMLItemPath finds the record element of feeds with non-English tags
|
|
// (<izdelki><izdelek>…): the most repeated element that has child elements, the
|
|
// shallowest on ties. Tolerates a truncated sample.
|
|
func guessRepeatedXMLItemPath(data []byte) string {
|
|
dec := xml.NewDecoder(bytes.NewReader(data))
|
|
dec.Strict = false
|
|
var stack []string
|
|
counts := map[string]int{}
|
|
hasChildren := map[string]bool{}
|
|
for {
|
|
tok, err := dec.Token()
|
|
if err != nil {
|
|
break
|
|
}
|
|
switch t := tok.(type) {
|
|
case xml.StartElement:
|
|
if len(stack) > 0 {
|
|
hasChildren[strings.Join(stack, "/")] = true
|
|
}
|
|
stack = append(stack, t.Name.Local)
|
|
counts[strings.Join(stack, "/")]++
|
|
case xml.EndElement:
|
|
if len(stack) > 0 {
|
|
stack = stack[:len(stack)-1]
|
|
}
|
|
}
|
|
}
|
|
best, bestN := "", 1
|
|
for p, n := range counts {
|
|
if !hasChildren[p] {
|
|
continue
|
|
}
|
|
depth, bestDepth := strings.Count(p, "/"), strings.Count(best, "/")
|
|
if n > bestN || (n == bestN && best != "" && (depth < bestDepth || (depth == bestDepth && p < best))) {
|
|
best, bestN = p, n
|
|
}
|
|
}
|
|
return best
|
|
}
|
|
|
|
func localNameEquals(n xml.Name, local string) bool {
|
|
return strings.EqualFold(n.Local, local)
|
|
}
|
|
|
|
// isXMLPropertyNameAttr lists attributes that name a property element
|
|
// (<lastnost naziv="…">, <param name="…">).
|
|
func isXMLPropertyNameAttr(local string) bool {
|
|
switch strings.ToLower(local) {
|
|
case "naziv", "name", "ime", "key", "label":
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func xmlPropertyLabel(attrs []xml.Attr) string {
|
|
for _, a := range attrs {
|
|
if isXMLPropertyNameAttr(a.Name.Local) {
|
|
return sanitizePathSegment(a.Value)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error) {
|
|
row := make(feedRow)
|
|
for _, a := range start.Attr {
|
|
key := "@" + a.Name.Local
|
|
row[key] = a.Value
|
|
row[start.Name.Local+"/"+key] = a.Value
|
|
}
|
|
var path []string
|
|
// propNames[i] is the label of path[i] when it is a named property inside a group,
|
|
// such as <dodatneLastnosti><lastnost naziv="Vrsta">Nahrbtnik</lastnost>… (else "").
|
|
// Its text is also stored under group/<label>; propCounts tracks group/leaf paths
|
|
// so the merged "all siblings" value can be dropped once two labels share it.
|
|
var propNames []string
|
|
propCounts := map[string]int{}
|
|
var paramName, paramValue string
|
|
for {
|
|
tok, err := dec.Token()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
switch t := tok.(type) {
|
|
case xml.StartElement:
|
|
path = append(path, t.Name.Local)
|
|
label := ""
|
|
if len(path) >= 2 {
|
|
label = xmlPropertyLabel(t.Attr)
|
|
}
|
|
if label != "" {
|
|
propCounts[strings.Join(path, "/")]++
|
|
}
|
|
propNames = append(propNames, label)
|
|
for _, a := range t.Attr {
|
|
key := strings.Join(path, "/") + "/@" + a.Name.Local
|
|
row["@"+a.Name.Local] = a.Value
|
|
row[key] = a.Value
|
|
}
|
|
case xml.EndElement:
|
|
if strings.EqualFold(t.Name.Local, "PARAM") && len(path) >= 2 && strings.EqualFold(path[len(path)-2], "PARAMS") {
|
|
name := strings.TrimSpace(paramName)
|
|
value := strings.TrimSpace(paramValue)
|
|
if name != "" && value != "" {
|
|
key := "PARAMS/" + sanitizePathSegment(name)
|
|
if key != "PARAMS/" {
|
|
row[key] = value
|
|
}
|
|
}
|
|
paramName, paramValue = "", ""
|
|
}
|
|
if len(path) == 0 {
|
|
for p, n := range propCounts {
|
|
if n > 1 {
|
|
delete(row, p) // "MicroUSB 1 m": every sibling's text merged
|
|
}
|
|
}
|
|
count := 0
|
|
for k := range row {
|
|
if strings.HasPrefix(k, "PARAMS/") && !strings.Contains(strings.TrimPrefix(k, "PARAMS/"), "/") {
|
|
count++
|
|
}
|
|
}
|
|
if count > 0 {
|
|
row["PARAMS"] = fmt.Sprintf("%d named attributes", count)
|
|
}
|
|
// Supplier feeds often publish additional images as numbered siblings.
|
|
images := make([]string, 0, 12)
|
|
for i := 1; i <= 50; i++ {
|
|
name := fmt.Sprintf("IMGURL_ALTERNATIVE_%02d", i)
|
|
if v := strings.TrimSpace(row[name]); v != "" {
|
|
images = append(images, v)
|
|
}
|
|
}
|
|
if len(images) > 0 {
|
|
row["ADDITIONAL_IMAGE_URLS"] = strings.Join(images, ",")
|
|
}
|
|
return row, nil
|
|
}
|
|
path = path[:len(path)-1]
|
|
propNames = propNames[:len(propNames)-1]
|
|
case xml.CharData:
|
|
text := strings.TrimSpace(string(t))
|
|
if text == "" || len(path) == 0 {
|
|
continue
|
|
}
|
|
if label := propNames[len(propNames)-1]; label != "" {
|
|
key := strings.Join(append(path[:len(path)-1:len(path)-1], label), "/")
|
|
if prev := row[key]; prev != "" && prev != text {
|
|
row[key] = prev + " " + text
|
|
} else {
|
|
row[key] = text
|
|
}
|
|
}
|
|
leaf := path[len(path)-1]
|
|
if len(path) >= 3 && strings.EqualFold(path[len(path)-3], "PARAMS") && strings.EqualFold(path[len(path)-2], "PARAM") {
|
|
if strings.EqualFold(leaf, "PARAM_NAME") {
|
|
paramName += text
|
|
continue
|
|
}
|
|
if strings.EqualFold(leaf, "VAL") {
|
|
paramValue += text
|
|
continue
|
|
}
|
|
if strings.EqualFold(leaf, "ORDER") {
|
|
continue
|
|
}
|
|
}
|
|
full := strings.Join(path, "/")
|
|
// Prefer nested path as source of truth; only set bare leaf when
|
|
// unique (no other nested field already owns this leaf name).
|
|
if prev, ok := row[full]; ok && prev != "" && prev != text {
|
|
row[full] = prev + " " + text
|
|
} else {
|
|
row[full] = text
|
|
}
|
|
if prev, ok := row[leaf]; !ok || prev == "" || prev == text || prev == row[full] {
|
|
row[leaf] = row[full]
|
|
}
|
|
}
|
|
}
|
|
}
|