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 // (…): 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 // (, ). 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 Nahrbtnik… (else ""). // Its text is also stored under group/