SPB Git

Repository Public

shopify.py 13.1 KB 302 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Fabri·Ka9# File             : fabrika/connectors/shopify.py10# Module           : fabrika11# Repository       : https://git.spboucher.ai/fabri-ka12# Created          : 2026-08-1213# Last Modified    : 2026-10-2814#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/shopify.py : connecteur générique Shopify — catalogue complet91#   via l'endpoint public /products.json (paginé, 250 produits/page).92# -----------------------------------------------------------------------------93from __future__ import annotations9495import threading96import time9798from ..schema import Product, parse_price99from .base import BaseConnector100101# Shopify applique une limite de débit PAR IP CLIENTE partagée entre toutes les102# boutiques derrière son CDN : on sérialise donc les requêtes Shopify103# globalement (toutes boutiques confondues) + retry sur 429.104_GLOBAL_LOCK = threading.Lock()105_MIN_INTERVAL = 0.7106_last_shopify_req = [0.0]107108109class _PageCapError(RuntimeError):110    """HTTP 400 « Page * Limit exceeds the 25000 limit » : /products.json111    refuse toute page au-delà de 25 000 produits — fin de pagination, pas112    une panne (ex. qublivre.ca, >25 k livres)."""113114115class _StorefrontLockedError(RuntimeError):116    """HTTP 401 sur /products.json : storefront verrouillé par mot de passe117    (mode « Bientôt ouvert », ex. fermeail-land.com) — rien n'est vendu118    publiquement, catalogue vide fidèle à la source, pas une panne."""119120121class ShopifyConnector(BaseConnector):122    platform = "shopify"123124    def _get_json(self, url: str) -> dict:125        """GET JSON via curl (l'empreinte TLS de python-requests déclenche le126        429 de Shopify sous volume ; curl passe). Throttle global + retry."""127        import json as _json128        import subprocess129        # boutique déjà identifiée comme bloquée (challenge anti-bot) :130        # rester sur Scrapfly pour les pages suivantes, sans re-tenter en direct131        if getattr(self, "_scrapfly_only", False):132            return self._scrapfly_json(url)133        last_err = None134        # myshopify.com bloque les UA navigateur mais accepte le UA curl par135        # défaut — ne pas passer -A sur ce domaine.136        import urllib.parse as _up137        _netloc = _up.urlparse(url).netloc138        _ua_args = ([] if _netloc.endswith(".myshopify.com")139                    else ["-A", self.session.headers["User-Agent"].split(" FabriKaBot")[0]])140        # 6 tentatives, backoff long sur 429 : les boutiques à panne141        # intermittente (ex. boutiquesoha.com) répondent après patience,142        # là où le repli Scrapfly renvoie parfois 422.143        for attempt in range(6):144            with _GLOBAL_LOCK:145                wait = _MIN_INTERVAL - (time.time() - _last_shopify_req[0])146                if wait > 0:147                    time.sleep(wait)148                _last_shopify_req[0] = time.time()149            p = subprocess.run(150                ["curl", "-sS", "--compressed", "-L", "--max-time", str(self.timeout),151                 *_ua_args,152                 "-w", "\n%{http_code}", url],153                capture_output=True, text=True, errors="replace")154            body, _, code = p.stdout.rpartition("\n")155            if code == "200":156                try:157                    return _json.loads(body)158                except _json.JSONDecodeError as exc:159                    last_err = exc160            elif code == "429":161                time.sleep(8 * (attempt + 1))162                last_err = RuntimeError("429 Too Many Requests")163            elif code == "400":164                raise _PageCapError(f"HTTP 400 {url}")165            elif code == "401":166                raise _StorefrontLockedError(f"HTTP 401 {url}")167            else:168                last_err = RuntimeError(f"HTTP {code or 'error'} {p.stderr[:120]}")169                time.sleep(2)170        # dernier recours : Scrapfly (anti-bot) si configuré171        from . import scrapfly172        if scrapfly.available():173            try:174                data = self._scrapfly_json(url)175                self._scrapfly_only = True176                return data177            except (_PageCapError, _StorefrontLockedError):178                raise179            except Exception as exc:180                last_err = exc181        raise RuntimeError(f"{url}: {last_err}")182183    def _scrapfly_json(self, url: str):184        """Scrapfly avec retry : le bypass anti-bot échoue parfois par intermittence."""185        from . import scrapfly186        last_err = None187        for attempt in range(3):188            try:189                return scrapfly.scrapfly_json(url)190            except Exception as exc:191                if "upstream 400" in str(exc):192                    raise _PageCapError(str(exc)) from exc193                if "upstream 401" in str(exc):194                    raise _StorefrontLockedError(str(exc)) from exc195                last_err = exc196                time.sleep(3 * (attempt + 1))197        raise RuntimeError(f"{url}: scrapfly: {last_err}")198199    def _domain_parked(self) -> bool:200        """Domaine parqué chez un revendeur : tout le site (accueil compris)201        répond un mini-HTML qui redirige vers /lander, la page de parking202        GoDaddy/Afternic — le Shopify a disparu avec le domaine (ex.203        artisacreations.ca, expiré le 2026-10-07, basculé sur le lander204        GoDaddy le 2026-10-12 alors que la boutique servait encore205        18 produits le matin même). Catalogue vide fidèle à la source, pas206        une panne. Un non-JSON sans ce marqueur continue de lever l'erreur —207        pas de masquage. Même garde-fou que WooCommerceConnector._domain_parked208        (sartcastik.com)."""209        try:210            r = self.get(self.base + "/")211        except Exception:212            return False213        body = r.text[:4096]214        return ('window.location.href="/lander' in body215                or "forsale.godaddy.com" in body216                or "afternic.com" in body)217218    def fetch(self) -> list[Product]:219        out: list[Product] = []220        page = 1221        while page <= self.max_pages:222            try:223                data = self._get_json(f"{self.base}/products.json?limit=250&page={page}")224            except _PageCapError:225                if page > 1 and out:226                    break227                raise228            except _StorefrontLockedError:229                break230            except Exception:231                if not out and self._domain_parked():232                    self.confirmed_empty = "domaine parqué (page de revente)"233                    return []234                raise235            items = data.get("products", [])236            if not items:237                break238            for it in items:239                variants = it.get("variants") or []240                prices = [parse_price(v.get("price")) for v in variants]241                prices = [p for p in prices if p]242                compare = [parse_price(v.get("compare_at_price")) for v in variants]243                compare = [c for c in compare if c]244                available = any(v.get("available", True) for v in variants) if variants else None245                det: dict = {}246                if variants:247                    vout = []248                    for v in variants[:20]:249                        vd = {"title": v.get("title", ""),250                              "price": parse_price(v.get("price")),251                              "sku": v.get("sku") or "",252                              "grams": v.get("grams"),253                              "available": v.get("available")}254                        vcmp = parse_price(v.get("compare_at_price"))255                        if vcmp:256                            vd["compare_at_price"] = vcmp257                        fi = v.get("featured_image") or {}258                        if isinstance(fi, dict) and fi.get("src"):259                            vd["image"] = fi["src"]260                        if v.get("requires_shipping") is False:261                            vd["requires_shipping"] = False262                        vout.append(vd)263                    det["variants"] = vout264                    skus = [v.get("sku") for v in variants if v.get("sku")]265                    if skus:266                        det["sku"] = skus[0]267                    grams = [v.get("grams") for v in variants if v.get("grams")]268                    if grams:269                        det["weight_grams"] = grams[0]270                options = [{"name": o.get("name", ""), "values": o.get("values") or []}271                           for o in (it.get("options") or [])272                           if (o.get("values") or []) != ["Default Title"]]273                if options:274                    det["options"] = options275                for k in ("published_at", "created_at", "updated_at"):276                    if it.get(k):277                        det[k] = it[k]278                _pmin = min(prices) if prices else None279                if compare and _pmin and max(compare) > _pmin:280                    det["on_sale"] = True281                out.append(Product(282                    store_id=self.store_id,283                    external_id=str(it["id"]),284                    url=f"{self.base}/products/{it.get('handle','')}",285                    title=it.get("title", ""),286                    description=it.get("body_html", "") or "",287                    price=min(prices) if prices else None,288                    price_max=max(prices) if prices else None,289                    compare_at_price=max(compare) if compare else None,290                    images=[im.get("src", "") for im in (it.get("images") or [])],291                    product_type=it.get("product_type", "") or "",292                    tags=(it.get("tags") if isinstance(it.get("tags"), list)293                          else [t.strip() for t in (it.get("tags") or "").split(",") if t.strip()]),294                    vendor=it.get("vendor", "") or "",295                    available=available,296                    details=det,297                ))298            if len(items) < 250:299                break300            page += 1301        return out302
Files main
Menu

Theme