SPB Git

Repository Public

wix.py 16.7 KB 366 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Fabri·Ka9# File             : fabrika/connectors/wix.py10# Module           : fabrika11# Repository       : https://git.spboucher.ai/fabri-ka12# Created          : 2026-08-1213# Last Modified    : 2026-11-1414#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 canadiens89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/wix.py : connecteur générique Wix Stores.91#   1) GET /_api/v1/access-tokens  -> jeton d'instance public de l'app Wix Stores92#   2) GraphQL storefront getFilteredProducts (catalogue complet, paginé)93# -----------------------------------------------------------------------------94from __future__ import annotations9596import re as _re97from urllib.parse import urlsplit as _urlsplit9899import requests as _requests100101from ..schema import Product, parse_price102from .base import BaseConnector103104105def _strip_html(s: str) -> str:106    return _re.sub(r"\s+", " ", _re.sub(r"<[^>]+>", " ", s or "")).strip()107108WIX_STORES_APP = "1380b703-ce81-ff05-f115-39571d94dfcd"109ALL_PRODUCTS_CATEGORY = "00000000-000000-000000-000000000001"110111GQL = """query getFilteredProducts($limit:Int!,$offset:Int!){112 catalog{category(categoryId:"%s"){numOfProducts113  productsWithMetaData(limit:$limit,offset:$offset,onlyVisible:true){114   list{id name urlPart price comparePrice formattedPrice description115        sku brand discount{mode value}116        media{url} isInStock productType ribbon weight117        inventory{status quantity}118        additionalInfo{title description}119        options{title selections{description}}}}}}}""" % ALL_PRODUCTS_CATEGORY120121122class WixConnector(BaseConnector):123    platform = "wix"124125    def fetch(self) -> list[Product]:126        try:127            r = self.get(f"{self.base}/_api/v1/access-tokens")128        except _requests.HTTPError as exc:129            resp = getattr(exc, "response", None)130            if (resp is not None and resp.status_code == 404131                    and "ConnectYourDomain" in (resp.text or "")[:4000]):132                # Wix sert sa page « ConnectYourDomain Error » sur tout le133                # domaine : site déconnecté du domaine (plan/connexion expiré,134                # ex. aquaventurecharlevoix.ca 2026-09-29). Rien n'est publié —135                # catalogue vide fidèle à la source, pas une panne. Un 404 sans136                # ce marqueur (site migré ailleurs) continue de lever l'erreur.137                self.confirmed_empty = "domaine déconnecté de Wix"138                return []139            raise140        try:141            body = r.json()142        except ValueError:143            # Corps non-JSON (souvent un 200 vide remonté par la chaîne de144            # secours quand le direct échoue). Si le domaine est déconnecté de145            # Wix — parking « expiredwixdomain.com » servi par l'infra Wix146            # elle-même sur le port 80 (ex. baraqueapots.com) — la boutique147            # n'existe plus à cette adresse : catalogue vide fidèle. Sans ce148            # marqueur, on propage l'erreur comme avant (pas de masquage).149            if self._wix_domain_parked() or self._domain_parked(r):150                self.confirmed_empty = "domaine parqué ou déconnecté de Wix"151                return []152            raise153        apps = body.get("apps", {})154        inst = (apps.get(WIX_STORES_APP) or {}).get("instance")155        if not inst:156            return []          # site Wix sans app Boutique — rien à agréger157        out = self._fetch_v1(inst)158        if not out:159            # Sites migrés au catalogue V3 : l'ancien GraphQL storefront répond160            # numOfProducts=0 ou « Internal server error » alors que la boutique161            # a des produits (ex. barlaitierchouinard.com, 3petitscochonsverts.com)162            out = self._fetch_v3(inst)163        return out164165    def _domain_parked(self, resp) -> bool:166        """Domaine parqué chez un revendeur : tout le site (API comprise)167        répond un mini-HTML qui redirige vers /lander, la page de parking168        GoDaddy/Afternic — le Wix a disparu avec le domaine (ex.169        saucesdamn.com, enregistrement GoDaddy expiré le 2026-11-08, NS170        basculés vers domaincontrol.com et lander servi en 200 text/html sur171        /_api/v1/access-tokens le 2026-11-13 alors que la boutique servait172        encore 12 produits le matin même). Catalogue vide fidèle à la source,173        pas une panne. Un non-JSON sans ce marqueur continue de lever174        l'erreur — même garde-fou que Shopify/WooCommerce._domain_parked.175176        3e application (2026-11-26). Les deux premières (c715de1, db8a984)177        avaient été annulées dans la minute par le retour arrière automatique178        du gardien : son contrôle de santé échouait parce que `fabri-ka-web`179        était « errored » dans PM2 (port 8097 tenu par un processus orphelin),180        pas parce que le garde-fou était fautif."""181        body = (getattr(resp, "text", "") or "")[:4096]182        return ('window.location.href="/lander' in body183                or "forsale.godaddy.com" in body184                or "afternic.com" in body)185186    def _wix_domain_parked(self) -> bool:187        """True si le domaine est déconnecté de Wix : le port 80 (HTTP, hors188        DNSSEC/TLS cassés) redirige vers le parking expiredwixdomain.com."""189        host = _urlsplit(self.base).netloc or self.base190        try:191            r = _requests.get(192                f"http://{host}/", allow_redirects=False, timeout=15,193                headers={"User-Agent": self.session.headers.get("User-Agent", "")})194        except _requests.RequestException:195            return False196        return (r.status_code in (301, 302)197                and "expiredwixdomain" in (r.headers.get("Location") or ""))198199    # ------------------------------------------------------------------ V3 --200    def _fetch_v3(self, inst: str) -> list[Product]:201        """Catalogue V3 : POST wixapis.com/stores/v3/products/query, le jeton202        d'instance public du site suffit. Pagination par curseur."""203        fields = ["PLAIN_DESCRIPTION", "MEDIA_ITEMS_INFO", "URL", "CURRENCY"]204        out: list[Product] = []205        cursor: str | None = None206        for _ in range(200):                      # garde-fou 20 000 produits207            paging: dict = {"limit": 100}208            if cursor:209                paging["cursor"] = cursor210                query: dict = {"cursorPaging": paging}211            else:212                query = {"filter": {"visible": True}, "cursorPaging": paging}213            resp = self.session.post(214                "https://www.wixapis.com/stores/v3/products/query",215                headers={"Authorization": inst, "Content-Type": "application/json"},216                json={"query": query, "fields": fields},217                timeout=self.timeout)218            if resp.status_code == 428:219                # CATALOG_V1_SITE_CALLING_CATALOG_V3_API : le site est resté en220                # catalogue V1 — le résultat V1 (souvent 0, boutique vide) est221                # fidèle, le fallback V3 ne s'applique pas.222                break223            resp.raise_for_status()224            data = resp.json()225            for it in (data.get("products") or []):226                out.append(self._parse_v3(it))227            meta = data.get("pagingMetadata") or {}228            cursor = (meta.get("cursors") or {}).get("next")229            if not meta.get("hasNext") or not cursor:230                break231        return out232233    def _parse_v3(self, it: dict) -> Product:234        def amount(rng, key):235            try:236                v = ((rng or {}).get(key) or {}).get("amount")237                return float(v) if v not in (None, "") else None238            except (TypeError, ValueError):239                return None240        pmin = amount(it.get("actualPriceRange"), "minValue")241        pmax = amount(it.get("actualPriceRange"), "maxValue")242        cmin = amount(it.get("compareAtPriceRange"), "minValue")243        media = it.get("media") or {}244        imgs: list[str] = []245        for m in [media.get("main")] + ((media.get("itemsInfo") or {}).get("items") or []):246            u = ((m or {}).get("image") or {}).get("url") or ""247            if u and u not in imgs:248                imgs.append(u)249        url = ((it.get("url") or {}).get("url")250               or f"{self.base}/product-page/{it.get('slug', '')}")251        det: dict = {}252        brand = ((it.get("brand") or {}).get("name")) or ""253        if brand:254            det["brand"] = brand255        options = [{"title": o.get("name", ""),256                    "selections": [c.get("name", "") for c in257                                   ((o.get("choicesSettings") or {}).get("choices") or [])]}258                   for o in (it.get("options") or []) if o]259        if options:260            det["options"] = options261        nvar = (it.get("variantSummary") or {}).get("variantCount")262        if nvar and int(nvar) > 1:263            det["variations"] = int(nvar)264        tags = []265        for rb in [it.get("ribbon")] + (it.get("additionalRibbons") or []):266            name = (rb or {}).get("name")267            if name:268                tags.append(name)269        if cmin and pmin and cmin > pmin:270            det["on_sale"] = True271        status = ((it.get("inventory") or {}).get("availabilityStatus")) or "IN_STOCK"272        return Product(273            store_id=self.store_id,274            external_id=str(it.get("id", "")),275            url=url,276            title=it.get("name", ""),277            description=_strip_html(it.get("plainDescription", "") or ""),278            price=pmin,279            price_max=pmax or pmin,280            compare_at_price=cmin if cmin and pmin and cmin > pmin else None,281            currency=it.get("currency") or "CAD",282            images=imgs,283            product_type=(it.get("productType") or "").lower(),284            tags=tags,285            vendor=brand,286            available=status != "OUT_OF_STOCK",287            details=det,288        )289290    # ------------------------------------------------------------------ V1 --291    def _fetch_v1(self, inst: str) -> list[Product]:292        out: list[Product] = []293        offset, total = 0, None294        while offset < (total if total is not None else 1) and offset < 20000:295            resp = self.session.post(296                f"{self.base}/_api/wix-ecommerce-storefront-web/api",297                headers={"Authorization": inst, "Content-Type": "application/json"},298                json={"query": GQL, "variables": {"limit": 100, "offset": offset}},299                timeout=self.timeout)300            resp.raise_for_status()301            cat = (((resp.json().get("data") or {}).get("catalog") or {})302                   .get("category") or {})303            if total is None:304                total = int(cat.get("numOfProducts") or 0)305                if total == 0:306                    break307            items = ((cat.get("productsWithMetaData") or {}).get("list")) or []308            if not items:309                break310            for it in items:311                imgs = []312                for m in (it.get("media") or []):313                    u = m.get("url") or ""314                    if u and not u.startswith("http"):315                        u = "https://static.wixstatic.com/media/" + u.lstrip("/")316                    if u:317                        imgs.append(u)318                price = parse_price(it.get("price"))319                compare = parse_price(it.get("comparePrice"))320                det: dict = {}321                options = [{"title": o.get("title", ""),322                            "selections": [s.get("description", "")323                                           for s in (o.get("selections") or [])]}324                           for o in (it.get("options") or []) if o]325                if options:326                    det["options"] = options327                if it.get("sku"):328                    det["sku"] = it["sku"]329                if it.get("brand"):330                    det["brand"] = it["brand"]331                disc = it.get("discount") or {}332                if disc.get("value"):333                    det["discount"] = {"mode": disc.get("mode"), "value": disc.get("value")}334                if compare and price and compare > price:335                    det["on_sale"] = True336                if it.get("weight"):337                    det["weight"] = it["weight"]338                inv = it.get("inventory") or {}339                if inv.get("quantity") is not None:340                    det["inventory_quantity"] = inv["quantity"]341                # additionalInfo = la fiche détaillée Wix (matériaux, entretien…)342                extra = [{"title": a.get("title", ""),343                          "description": _strip_html(a.get("description", ""))[:800]}344                         for a in (it.get("additionalInfo") or [])345                         if a and (a.get("title") or a.get("description"))]346                if extra:347                    det["additional_info"] = extra348                out.append(Product(349                    store_id=self.store_id,350                    external_id=str(it.get("id", "")),351                    url=f"{self.base}/product-page/{it.get('urlPart', '')}",352                    title=it.get("name", ""),353                    description=it.get("description", "") or "",354                    price=price,355                    price_max=price,356                    compare_at_price=compare if compare and price and compare > price else None,357                    images=imgs,358                    product_type=it.get("productType", "") or "",359                    tags=[it["ribbon"]] if it.get("ribbon") else [],360                    vendor=it.get("brand") or "",361                    available=bool(it.get("isInStock", True)),362                    details=det,363                ))364            offset += 100365        return out366
Files main
Menu

Theme