Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Fabri·Ka9# File : fabrika/connectors/woocommerce.py10# Module : fabrika11# Repository : https://git.spboucher.ai/fabri-ka12# Created : 2026-08-1213# Last Modified : 2026-10-3014#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Fabri-Ka — Agrégateur de produits québécois89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/woocommerce.py : connecteur générique WooCommerce — catalogue91# complet via la Store API publique /wp-json/wc/store/v1/products.92# -----------------------------------------------------------------------------93from __future__ import annotations9495import re96from urllib.parse import urlparse9798from ..schema import Product99from .base import BaseConnector100101102class WooCommerceConnector(BaseConnector):103 platform = "woocommerce"104105 # Certains hébergeurs bloquent le chemin /wp-json/ (404 serveur) alors que106 # l'API REST reste servie via la forme ?rest_route= (ex. colorantic.com).107 _use_rest_route = False108109 # Vieux WooCommerce (< 6.4) : la Store API n'est pas versionnée —110 # /wc/store/products répond mais /wc/store/v1/products donne rest_no_route111 # (ex. magillhats.com, restauré sur une vieille sauvegarde). Vide = sans /v1.112 _api_version = "v1"113114 def _store_api_url(self, path: str, query: str = "") -> str:115 """URL Store API : /wp-json/wc/store/v1/<path> ou ?rest_route= en secours."""116 ver = f"{self._api_version}/" if self._api_version else ""117 if self._use_rest_route:118 sep = "&" if query else ""119 return f"{self.base}/?rest_route=/wc/store/{ver}{path}{sep}{query}"120 sep = "?" if query else ""121 return f"{self.base}/wp-json/wc/store/{ver}{path}{sep}{query}"122123 def _get_items(self, url: str):124 """JSON direct, sinon Scrapfly (Cloudflare & cie) en dernier recours."""125 import time as _time126 try:127 for _attempt in range(8):128 try:129 r = self.get(url)130 break131 except Exception as exc508:132 code = getattr(getattr(exc508, "response", None), "status_code", None)133 # hébergement à bout de ressources (CloudLinux « Resource Limit134 # Is Reached » 508 / « Insufficient Storage » 507, ex.135 # magillhats.com) : intermittent — ~1 requête sur 7 passe,136 # indépendant de l'IP; réessayer brièvement plutôt qu'échouer137 if code in (507, 508) and _attempt < 7:138 _time.sleep(3)139 continue140 raise141 try:142 return r.json()143 except ValueError:144 import json as _json145 # Certains serveurs WP émettent un BOM UTF-8 (\xef\xbb\xbf) avant146 # le JSON — utf-8-sig le retire proprement (ex. cabanedupicbois.com).147 try:148 return _json.loads(r.content.decode("utf-8-sig"))149 except (ValueError, UnicodeDecodeError):150 pass151 # Certains plugins WP (ex. recipe_for_product sur152 # domainevallierrobert.ca) émettent du HTML avant le JSON REST —153 # on cherche le premier '[' ou '{' et on parse depuis là.154 for marker in (b"[", b"{"):155 idx = r.content.find(marker)156 if idx > 0:157 try:158 return _json.loads(r.content[idx:])159 except ValueError:160 pass161 raise ValueError(f"Impossible de parser le JSON de {url}")162 except Exception as exc:163 from . import scrapfly164 if scrapfly.available():165 return scrapfly.scrapfly_json(url)166 raise exc167168 def _html_fallback(self) -> list[Product]:169 """Fallback HTML quand la Store API WooCommerce retourne 500 (erreur serveur).170171 Découvre les URLs produit depuis l'accueil et les pages catégories WooCommerce,172 puis extrait le JSON-LD Product de chaque page. Utilisé quand /wp-json/ est173 cassé mais que les pages HTML sont servies depuis le cache (ex. WP Super Cache).174 """175 from .generic import extract_product176177 host = urlparse(self.base).netloc178179 # Accueil + slugs de boutique courants (FR d'abord)180 discovery = [self.base + "/"]181 for path in ("/shop/", "/boutique/", "/boutique-en-ligne/",182 "/produits/", "/products/"):183 discovery.append(self.base + path)184185 product_urls: set[str] = set()186187 for page_url in discovery:188 try:189 r = self.session.get(page_url, timeout=self.timeout)190 if r.status_code != 200:191 continue192 html = r.text193 # Produits WooCommerce FR (/produit/) et EN (/product/)194 found = set(re.findall(195 rf'href="(https?://{re.escape(host)}/(?:produit|product)/[^"#?]+)"',196 html))197 product_urls |= found198 # Catégories WooCommerce FR (/categorie-produit/) et EN (/product-category/)199 cat_links = set(re.findall(200 rf'href="(https?://{re.escape(host)}/(?:categorie-produit|product-category)/[^"#?]+)"',201 html))202 for cat_url in cat_links:203 try:204 r2 = self.session.get(cat_url, timeout=self.timeout)205 if r2.status_code == 200:206 product_urls |= set(re.findall(207 rf'href="(https?://{re.escape(host)}/(?:produit|product)/[^"#?]+)"',208 r2.text))209 except Exception:210 pass211 except Exception:212 pass213214 out: list[Product] = []215 for url in product_urls:216 try:217 r = self.session.get(url, timeout=self.timeout)218 if r.status_code != 200:219 continue220 info = extract_product(url, r.text)221 if not info:222 continue223 slug = url.rstrip("/").split("/")[-1][:80]224 det: dict = {}225 if info.get("sku"):226 det["sku"] = info["sku"]227 if info.get("rating"):228 det["average_rating"] = info["rating"]229 if info.get("review_count"):230 det["review_count"] = info["review_count"]231 out.append(Product(232 store_id=self.store_id,233 external_id=slug or url,234 url=url,235 title=info["title"],236 description=info.get("description") or "",237 price=info["price"],238 price_max=info.get("price_max") or info["price"],239 currency=info.get("currency") or "CAD",240 images=info.get("images") or ([info["image"]] if info.get("image") else []),241 vendor=info.get("brand") or "",242 available=info.get("available"),243 details=det,244 ))245 except Exception:246 pass247 return out248249 @staticmethod250 def _is_404(exc: Exception) -> bool:251 r = getattr(exc, "response", None)252 if r is not None and getattr(r, "status_code", None) == 404:253 return True254 return "upstream 404" in str(exc)255256 def _domain_parked(self) -> bool:257 """Domaine parqué chez un revendeur : tout le site (accueil compris)258 répond un mini-HTML qui redirige vers /lander, la page « for sale »259 Afternic/GoDaddy — le WordPress a disparu avec le domaine (ex.260 sartcastik.com, NS basculés vers ns3/ns4.afternic.com le 2026-10-02261 alors que la boutique servait encore 616 produits la veille).262 Catalogue vide fidèle à la source, pas une panne. Un non-JSON sans ce263 marqueur continue de lever l'erreur — pas de masquage."""264 try:265 r = self.get(self.base + "/")266 except Exception:267 return False268 body = r.text[:4096]269 return ('window.location.href="/lander' in body270 or "forsale.godaddy.com" in body271 or "afternic.com" in body)272273 def _woo_uninstalled(self) -> bool:274 """WordPress vivant mais WooCommerce désinstallé : l'index REST /wp-json/275 répond (wp/v2 présent) sans plus aucun namespace wc* — la boutique a été276 retirée du site (ex. labete.ca, restaurant repassé site vitrine).277 Catalogue vide fidèle à la source, pas une panne."""278 try:279 data = self._get_items(f"{self.base}/wp-json/")280 except Exception:281 return False282 ns = data.get("namespaces") if isinstance(data, dict) else None283 if not isinstance(ns, list) or "wp/v2" not in ns:284 return False285 return not any(str(n).startswith("wc") for n in ns)286287 @staticmethod288 def _seq(v) -> list:289 # certains filtres WP sérialisent un tableau PHP à clés non290 # séquentielles en objet JSON ({"1": {...}} au lieu de [{...}]) —291 # constaté sur les images d'artisansduvitrail.com; tolérer les deux292 if isinstance(v, dict):293 return list(v.values())294 return v or []295296 def _parse_item(self, it: dict) -> Product:297 """Mappe un produit Store API (liste ou fiche unitaire) vers Product."""298 prices = it.get("prices") or {}299 unit = 10 ** int(prices.get("currency_minor_unit", 2))300 def money(v):301 try:302 return int(v) / unit if v not in (None, "") else None303 except (TypeError, ValueError):304 return None305 price = money(prices.get("price"))306 pr = prices.get("price_range") or {}307 pmin, pmax = money(pr.get("min_amount")), money(pr.get("max_amount"))308 cats = [c.get("name", "") for c in self._seq(it.get("categories")) if isinstance(c, dict)]309 brands = [b.get("name", "") for b in self._seq(it.get("brands"))310 if isinstance(b, dict) and b.get("name")]311 det: dict = {}312 try:313 if float(it.get("average_rating") or 0) > 0:314 det["average_rating"] = float(it["average_rating"])315 except (TypeError, ValueError):316 pass317 if it.get("review_count"):318 det["review_count"] = int(it["review_count"])319 if it.get("sku"):320 det["sku"] = it["sku"]321 if it.get("weight"):322 det["weight"] = it["weight"]323 det["formatted_weight"] = it.get("formatted_weight") or ""324 dims = it.get("dimensions") or {}325 if any(dims.get(k) for k in ("length", "width", "height")):326 det["dimensions"] = dims327 det["formatted_dimensions"] = it.get("formatted_dimensions") or ""328 # certains thèmes renvoient attributes/terms comme simples329 # chaînes (constaté sur norseco.com) — tolérer les deux formes330 def _nm(x):331 return x.get("name", "") if isinstance(x, dict) else str(x)332 attributes = []333 for a in self._seq(it.get("attributes")):334 terms = self._seq(a.get("terms")) if isinstance(a, dict) else []335 attributes.append({"name": _nm(a),336 "terms": [_nm(t) for t in terms]})337 if attributes:338 det["attributes"] = attributes339 if it.get("low_stock_remaining"):340 det["low_stock_remaining"] = it["low_stock_remaining"]341 if it.get("is_on_backorder"):342 det["is_on_backorder"] = True343 if it.get("on_sale"):344 det["on_sale"] = True345 if cats:346 det["categories"] = [c for c in cats if c]347 variations = self._seq(it.get("variations"))348 if variations:349 det["variations"] = len(variations)350 vout = []351 for v in variations[:20]:352 if not isinstance(v, dict):353 continue354 attrs = [f"{_nm(a)}: {a.get('value', '')}" if isinstance(a, dict) else str(a)355 for a in (v.get("attributes") or [])]356 if attrs:357 vout.append({"title": " / ".join(x for x in attrs if x)})358 if vout:359 det["variants"] = vout360 # description : courte + longue concaténées (l'ancienne règle361 # « courte OU longue » jetait la description riche sur 37 % des fiches)362 short = (it.get("short_description") or "").strip()363 long_ = (it.get("description") or "").strip()364 desc = short if long_ in ("", short) else (long_ if not short else f"{short} {long_}")365 return Product(366 store_id=self.store_id,367 external_id=str(it["id"]),368 url=it.get("permalink", ""),369 title=it.get("name", ""),370 description=desc,371 price=pmin or price,372 price_max=pmax or price,373 compare_at_price=money(prices.get("regular_price"))374 if prices.get("sale_price") and prices.get("sale_price") != prices.get("regular_price")375 else None,376 currency=prices.get("currency_code", "CAD"),377 images=[im.get("src", "") for im in self._seq(it.get("images"))378 if isinstance(im, dict)],379 product_type=", ".join(cats),380 tags=[t.get("name", "") for t in self._seq(it.get("tags"))381 if isinstance(t, dict)],382 vendor=brands[0] if brands else "",383 available=bool(it.get("is_in_stock", True)),384 details=det,385 )386387 def _sitemap_slug_fallback(self) -> list[Product]:388 """Fallback quand la liste Store API est vide mais que des produits existent.389390 Certaines boutiques (ex. auxjardins.ca, saisonnière) masquent tout leur391 catalogue (catalog_visibility: hidden) : la liste /products retourne []392 mais les fiches unitaires /products/<slug> répondent. On découvre les393 slugs via le sitemap produits (Yoast product-sitemap.xml ou natif394 wp-sitemap.xml) et on aspire chaque fiche via la Store API.395 """396 import xml.etree.ElementTree as ET397398 def locs(url: str) -> list[str]:399 try:400 r = self.get(url)401 root = ET.fromstring(r.content)402 # <loc> du namespace sitemap seulement : les sitemaps Yoast/AIOSEO403 # embarquent aussi des <image:loc> (URLs wp-content à exclure)404 out = [e.text.strip() for e in root.iter(405 "{http://www.sitemaps.org/schemas/sitemap/0.9}loc") if e.text]406 if not out:407 out = [e.text.strip() for e in root.iter()408 if e.tag.endswith("loc") and e.text409 and "/wp-content/" not in e.text]410 return out411 except Exception:412 return []413414 product_urls: list[str] = []415 # Yoast : product-sitemap.xml (parfois paginé product-sitemap2.xml —416 # couvert car listé dans sitemap_index.xml)417 candidates = [f"{self.base}/product-sitemap.xml"]418 for index in (f"{self.base}/sitemap_index.xml", f"{self.base}/wp-sitemap.xml"):419 candidates += [u for u in locs(index)420 if re.search(r"(?:^|/)(?:product-sitemap|wp-sitemap-posts-product-)[^/]*\.xml$", u)]421 seen: set[str] = set()422 for sm in candidates:423 if sm in seen:424 continue425 seen.add(sm)426 # base de permalien standard (/produit/, /product/) OU personnalisée427 # (ex. /project/ sur mobilierurbain.ca) : les sitemaps candidats ne428 # listent que des produits, on accepte tout URL /base/slug/429 product_urls += [u for u in locs(sm)430 if re.search(r"/(?:produit|product)/[^/]+/?$", u)431 or re.fullmatch(r"https?://[^/]+/[^/]+/[^/]+/?", u)]432 slugs = []433 slug_seen: set[str] = set()434 for u in product_urls:435 slug = u.rstrip("/").split("/")[-1]436 if slug and slug not in slug_seen:437 slug_seen.add(slug)438 slugs.append(slug)439 out: list[Product] = []440 for slug in slugs:441 try:442 it = self._get_items(self._store_api_url(f"products/{slug}"))443 if isinstance(it, dict) and it.get("id"):444 out.append(self._parse_item(it))445 except Exception:446 continue447 return out448449 def fetch(self) -> list[Product]:450 out: list[Product] = []451 page = 1452 first_page_exc: Exception | None = None453 while page <= self.max_pages:454 try:455 items = self._get_items(self._store_api_url("products", f"per_page=100&page={page}"))456 except Exception as exc:457 if page != 1:458 break459 items = None460 if self._api_version:461 # vieux WooCommerce (< 6.4) : Store API non versionnée462 # /wc/store/products, la route /v1/ donne rest_no_route —463 # tenter quel que soit l'échec, un 508 intermittent peut464 # masquer le 404 (ex. magillhats.com)465 self._api_version = ""466 try:467 items = self._get_items(self._store_api_url("products", f"per_page=100&page={page}"))468 except Exception:469 self._api_version = "v1"470 if items is None and not self._use_rest_route:471 # chemin /wp-json/ bloqué par l'hébergeur ? retenter via ?rest_route=472 self._use_rest_route = True473 try:474 items = self._get_items(self._store_api_url("products", f"per_page=100&page={page}"))475 except Exception:476 pass477 if items is None and self._api_version:478 # permaliens WP « plain » (wp-json 404) + Store API non479 # versionnée : seule ?rest_route=/wc/store/products480 # (sans /v1) répond — ex. veroniquedaragon.com481 self._api_version = ""482 try:483 items = self._get_items(self._store_api_url("products", f"per_page=100&page={page}"))484 except Exception:485 self._api_version = "v1"486 if items is None:487 self._use_rest_route = False488 if items is None:489 first_page_exc = exc490 break491 if not isinstance(items, list) or not items:492 break493 for it in items:494 out.append(self._parse_item(it))495 if len(items) < 100:496 break497 page += 1498499 if first_page_exc is not None and not out:500 # Store API inaccessible dès la 1ʳᵉ page → fallback HTML + JSON-LD501 html_out = self._html_fallback()502 if html_out:503 return html_out504 # Route liste cassée (500 fatal) mais fiches unitaires parfois505 # saines (ex. mobilierurbain.ca) : tenter sitemap + fiches par slug506 slug_out = self._sitemap_slug_fallback()507 if slug_out:508 return slug_out509 if self._is_404(first_page_exc) and self._woo_uninstalled():510 self.confirmed_empty = "WooCommerce désinstallé du site"511 return []512 if self._domain_parked():513 self.confirmed_empty = "domaine parqué (page de revente)"514 return []515 raise first_page_exc516517 if not out and first_page_exc is None:518 # Liste vide mais API saine → catalogue peut-être masqué519 # (catalog_visibility) : tenter le sitemap produits + fiches par slug520 out = self._sitemap_slug_fallback()521522 return out523