This commit is contained in:
greeneclipse committed 2026-10-15 21:22:43 +02:00
1 parent 04794aea54
commit cfd31f398c
61 files changed
+2062 -254

No files matched your search

@@ -1,8 +1,12 @@
package httpapi
import (
"encoding/json"
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
@@ -191,6 +195,50 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
return
}
if strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "application/json") {
var req struct {
URL string `json:"url"`
RequestHeaders map[string]string `json:"request_headers"`
Format string `json:"format"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid JSON request")
return
}
if strings.TrimSpace(req.URL) == "" {
Error(w, http.StatusBadRequest, "url required")
return
}
source, err := feeds.DownloadImportSource(r.Context(), req.URL, req.RequestHeaders, catalogMaxUpload)
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not download import URL", err, feeds.ClientError)
return
}
defer source.Close()
var data io.Reader = source
if strings.EqualFold(req.Format, "json") || strings.Contains(strings.ToLower(req.URL), "json") {
data, err = catalog.JSONImportAsCSV(source, kind)
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "invalid JSON import", err, catalog.ClientError)
return
}
}
var result catalog.ImportResult
switch kind {
case "categories":
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, data)
case "attributes":
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, data)
case "products":
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, data, nil)
}
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "import failed", err, catalog.ClientError)
return
}
JSON(w, http.StatusOK, map[string]any{"kind": kind, "import": result, "source": "url"})
return
}
if err := r.ParseMultipartForm(catalogMaxUpload); err != nil {
Error(w, http.StatusBadRequest, "invalid multipart form")
return
@@ -228,14 +276,22 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
defer f.Close()
var result any
var input io.Reader = f
if strings.EqualFold(filepath.Ext(header.Filename), ".json") || strings.Contains(strings.ToLower(header.Header.Get("Content-Type")), "application/json") {
input, err = catalog.JSONImportAsCSV(f, kind)
if err != nil {
Error(w, http.StatusBadRequest, err.Error())
return
}
}
switch kind {
case "categories":
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, f)
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, input)
case "attributes":
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, f)
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, input)
case "products":
fid := fileID
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, f, &fid)
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, input, &fid)
}
if err != nil {
public := "import failed"
+37 -8
View File
@@ -1,6 +1,7 @@
package httpapi
import (
"encoding/json"
"errors"
"fmt"
"net/http"
@@ -46,11 +47,12 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
}
var body struct {
Name string `json:"name"`
URL string `json:"url"`
ItemPath string `json:"item_path"`
FeedType string `json:"feed_type"`
SyncIntervalMinutes int `json:"sync_interval_minutes"`
Name string `json:"name"`
URL string `json:"url"`
ItemPath string `json:"item_path"`
FeedType string `json:"feed_type"`
SyncIntervalMinutes int `json:"sync_interval_minutes"`
RequestHeaders map[string]string `json:"request_headers"`
}
if err := DecodeJSON(r, &body); err != nil {
Error(w, http.StatusBadRequest, "invalid json")
@@ -62,6 +64,7 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
ItemPath: body.ItemPath,
FeedType: body.FeedType,
SyncIntervalMinutes: body.SyncIntervalMinutes,
RequestHeaders: body.RequestHeaders,
})
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
@@ -81,6 +84,13 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
feedType := strings.TrimSpace(r.FormValue("feed_type"))
itemPath := strings.TrimSpace(r.FormValue("item_path"))
interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes")))
headers := map[string]string{}
if raw := strings.TrimSpace(r.FormValue("request_headers")); raw != "" {
if err := json.Unmarshal([]byte(raw), &headers); err != nil {
Error(w, http.StatusBadRequest, "invalid request_headers JSON")
return
}
}
file, header, fileErr := r.FormFile("file")
var options map[string]any
@@ -107,10 +117,15 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
"source_path": pathStr,
"source_file_id": fileID,
"source_filename": fileName,
"source_kind": "csv",
"source_kind": feedType,
}
if feedType == "" {
feedType = "csv"
if strings.HasSuffix(strings.ToLower(header.Filename), ".xml") {
feedType = "xml"
} else if strings.HasSuffix(strings.ToLower(header.Filename), ".json") {
feedType = "json"
}
}
if fid, err := uuid.Parse(fileID); err == nil {
_, _ = s.Catalog.UpdateFileStatus(r.Context(), cid, fid, "uploaded", map[string]any{
@@ -131,6 +146,7 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
FeedType: feedType,
SyncIntervalMinutes: interval,
Options: options,
RequestHeaders: headers,
})
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
@@ -192,7 +208,8 @@ func (s *Server) handleDeleteFeed(w http.ResponseWriter, r *http.Request) {
Error(w, http.StatusBadRequest, "invalid id")
return
}
if err := s.Feeds.Delete(r.Context(), cid, id); err != nil {
deletedUnprocessed, err := s.Feeds.DeleteWithCleanup(r.Context(), cid, id)
if err != nil {
if feeds.IsNotFound(err) {
Error(w, http.StatusNotFound, "not found")
return
@@ -200,7 +217,10 @@ func (s *Server) handleDeleteFeed(w http.ResponseWriter, r *http.Request) {
Error(w, http.StatusInternalServerError, "delete failed")
return
}
JSON(w, http.StatusOK, map[string]any{"id": id.String(), "deleted": true})
JSON(w, http.StatusOK, map[string]any{
"id": id.String(), "deleted": true,
"deleted_unprocessed_products": deletedUnprocessed,
})
}
func (s *Server) handleSyncFeed(w http.ResponseWriter, r *http.Request) {
@@ -584,6 +604,15 @@ func (s *Server) handlePublicExportCSV(w http.ResponseWriter, r *http.Request) {
}
}
func (s *Server) handlePublicExportJSON(w http.ResponseWriter, r *http.Request) {
token := chi.URLParam(r, "token")
lw := &lazyHeaderWriter{ResponseWriter: w, contentType: "application/json; charset=utf-8"}
if err := s.Feeds.PublicExportJSON(r.Context(), lw, token); err != nil {
if !lw.wrote {
writePublicExportError(w, err)
}
}
}
func writePublicExportError(w http.ResponseWriter, err error) {
// Format mismatch must look identical to unknown tokens so probing .xml/.csv
// cannot confirm whether a guessed public_token exists.
+1
View File
@@ -301,6 +301,7 @@ func (s *Server) Router() http.Handler {
r.Get("/support-kb/{filename}", s.handlePublicKBImage)
r.With(s.RateLimitPublicExport).Get("/export-feeds/{token}.xml", s.handlePublicExportXML)
r.With(s.RateLimitPublicExport).Get("/export-feeds/{token}.csv", s.handlePublicExportCSV)
r.With(s.RateLimitPublicExport).Get("/export-feeds/{token}.json", s.handlePublicExportJSON)
r.Get("/unsubscribe", s.handlePublicUnsubscribeGet)
r.Post("/unsubscribe", s.handlePublicUnsubscribePost)
r.NotFound(func(w http.ResponseWriter, _ *http.Request) {
@@ -43,8 +43,8 @@ func presentV1ExportFeed(item map[string]any) map[string]any {
if token, _ := item["public_token"].(string); token != "" {
format := strings.ToLower(strings.TrimSpace(fmt.Sprint(item["format"])))
ext := "xml"
if format == "csv" {
ext = "csv"
if format == "csv" || format == "json" {
ext = format
}
path := "/api/public/export-feeds/" + token + "." + ext
// Only advertise the matching extension — wrong-format URLs 404 and must not
@@ -157,8 +157,8 @@ func (s *Server) handleV1GenerateExportFeed(w http.ResponseWriter, r *http.Reque
format = strings.ToLower(strings.TrimSpace(fmt.Sprint(result["format"])))
}
ext := "xml"
if format == "csv" {
ext = "csv"
if format == "csv" || format == "json" {
ext = format
}
token, _ := feed["public_token"].(string)
downloadURL := fmt.Sprintf("/api/export-feeds/%s/%s", id.String(), ext)
@@ -0,0 +1,27 @@
package httpapi
import (
"strings"
"testing"
)
func TestPublicJSONExportOnlyAdvertisesJSON(t *testing.T) {
item := presentV1ExportFeed(map[string]any{
"id": "00000000-0000-0000-0000-000000000001",
"name": "JSON catalog", "format": "json", "public_token": "exampleToken",
})
urls, ok := item["public_urls"].(map[string]string)
if !ok {
t.Fatalf("public_urls missing: %#v", item)
}
got := urls["json"]
if got != "/api/public/export-feeds/exampleToken.json" {
t.Fatalf("json URL = %q", got)
}
if _, exists := urls["xml"]; exists {
t.Fatal("JSON export must not advertise XML URL")
}
if !strings.HasSuffix(urls["token"], ".json") {
t.Fatalf("token URL = %q", urls["token"])
}
}
+46 -20
View File
@@ -17,8 +17,10 @@ info:
## Authentication
All /api/v1 operations require a company API key (Bearer or X-API-Key) except
GET /health and GET /openapi.yaml.
Public /api/v1 operations require a company API key (Bearer or X-API-Key)
except GET /health and GET /openapi.yaml. Dashboard-only Team/Admin
operations described separately use a signed-in session and CSRF header;
they are not executable with a company API key.
Document-level security is BearerAuth OR ApiKeyAuth (same key value).
Do not send dashboard session cookies or CSRF tokens to /api/v1.
@@ -36,7 +38,8 @@ info:
1. Sign in at https://api.descrybe.io
2. Open Settings -> API keys (/settings?tab=api-keys)
3. Company admins create a key via dashboard POST /api/api-keys
3. Company admins or teammates granted API Keys management permission create
a key via dashboard POST /api/api-keys
(session cookie + CSRF; not this public OpenAPI surface). The secret is
shown once and starts with dk_.
4. Store it securely. Later list/revoke shows only key_prefix (first 10
@@ -134,8 +137,10 @@ info:
items[].description on the start body is optional source text the model may
rewrite. Poll GET /products/process/{id} for the generated HTML.
meta_title / meta_description are separate short SEO fields and may be
omitted depending on company configuration.
meta_title / meta_description are separate short SEO fields. The SEO-only
processing_type seo_meta generates these fields without replacing saved
product titles or descriptions. Company feature policies may still suppress
metadata output.
Note: Dashboard JSON under /api/* uses session cookies + CSRF and is separate
from this public API-key surface. Other path aliases
@@ -2136,7 +2141,7 @@ paths:
application/json:
schema:
type: object
required: [name, item_path]
required: [name]
properties:
name:
type: string
@@ -2144,7 +2149,9 @@ paths:
item_path:
type: string
description: |
XML item xpath / path stored in options.item_path (e.g. channel/item). Required.
Optional XML record path stored in options.item_path (e.g. SHOPITEM).
Auto-detection is available for typical feeds. For JSON use the item
array path (e.g. results or data.products) when needed.
url:
type: string
format: uri
@@ -2156,7 +2163,8 @@ paths:
enum:
- xml
- csv
description: Source format. xml (default) or csv.
- json
description: Source format. xml, csv or json; defaults to xml when not detected.
sync_interval_minutes:
type: integer
minimum: 1
@@ -2366,13 +2374,14 @@ paths:
description: Remote feed URL, or null to clear
item_path:
type: string
description: XML item xpath / path (stored in options.item_path)
description: Optional XML record path or JSON array path (stored in options.item_path)
feed_type:
type: string
enum:
- xml
- csv
description: Source format. xml or csv.
- json
description: Source format. xml, csv or json.
status:
type: string
description: |
@@ -2472,7 +2481,12 @@ paths:
tags:
- Feeds
summary: Delete feed
description: "Company-admin only. Flat { id, deleted: true } (not a message envelope)."
description: >-
Company-admin only. Atomically removes the input feed and its exclusively
owned, unprocessed or failed raw products. Previously processed products
are retained; active processing rows are not deleted, and products shared
with another existing feed are reassigned to that feed. Flat response
with id, deleted, and deleted_unprocessed_products (no message envelope).
responses:
'200':
description: Feed deleted. Flat FeedDeleted when handleDeleteFeed succeeds. Requires company-admin
@@ -2484,6 +2498,7 @@ paths:
example:
id: 22222222-2222-2222-2222-222222222222
deleted: true
deleted_unprocessed_products: 18
'400':
description: Invalid feed UUID.
content:
@@ -2866,7 +2881,7 @@ paths:
properties:
item_path:
type: string
description: Optional XML item path hint; inferred when omitted
description: Optional XML record path or JSON array path hint; inferred when omitted
example:
item_path: channel/item
responses:
@@ -3165,7 +3180,8 @@ paths:
enum:
- xml
- csv
description: Output format. xml or csv (required).
- json
description: Output format. xml, csv or json (required).
source_feed_id:
type: string
format: uuid
@@ -3660,7 +3676,7 @@ paths:
- Export feeds
summary: Rotate public export URL token
description: |
Replaces public_token so the previous /api/public/export-feeds/{token}.{xml|csv}
Replaces public_token so the previous /api/public/export-feeds/{token}.{xml|csv|json}
URL stops working immediately. Requires company admin (or platform staff).
Response is a flat ExportFeedDetail including the new public_token.
parameters:
@@ -5228,11 +5244,13 @@ components:
description: |
full (default) runs the whole pipeline including AI enhance, which
writes formula-driven HTML descriptions (not a one- or two-sentence
blurb). Named steps category|title|description|attributes (string or
blurb). Named steps category|title|description|attributes|seo_meta (string or
array of those steps); dual-mode also accepts v2 dashboard types such as
normalize_only, enhance_only, attributes_only, eprel_only, categorize_only
(ParseV1ProcessingType). Alias processingType accepted when values match.
The description step still emits the category formula HTML body.
The description step emits the category formula HTML body.
seo_meta generates meta_title and meta_description, preserving
existing product titles and descriptions.
oneOf:
- type: string
enum:
@@ -5241,6 +5259,7 @@ components:
- title
- description
- attributes
- seo_meta
- normalize_only
- enhance
- enhance_only
@@ -5261,6 +5280,7 @@ components:
- title
- description
- attributes
- seo_meta
processingType:
description: CamelCase alias of processing_type (must match if both set)
oneOf:
@@ -5272,7 +5292,7 @@ components:
type: array
items:
type: string
description: Dashboard fine-grained steps; used when processing_type omitted
description: Informational dashboard selection; execution uses processing_type.
examples:
by_ean:
summary: "items[].ean (preferred)"
@@ -5318,15 +5338,15 @@ components:
processing_type:
type: string
description: |
full (default) or a named dashboard step (category, title, description,
attributes, normalize_only, enhance_only, …).
full (default) or a named processing mode (title, description, seo_meta,
seo_meta, attributes, normalize_only, enhance_only, …).
default: full
example: full
processing_types:
type: array
items:
type: string
description: Optional fine-grained steps (dashboard); StartJob uses processing_type
description: Informational dashboard selection; execution uses processing_type. For seo_meta alone set processing_type to seo_meta.
example:
raw_product_ids:
- 2c5ea4c0-4067-4e44-8c5a-9a8b7c6d5e4f
@@ -6064,12 +6084,18 @@ components:
required:
- id
- deleted
- deleted_unprocessed_products
properties:
id:
type: string
format: uuid
deleted:
type: boolean
deleted_unprocessed_products:
type: integer
format: int64
minimum: 0
description: Number of unprocessed/failed raw products deleted with this feed.
PreparedCampaign:
type: object
properties: