Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/gatsby_dealers.py10# Module : autoka11# Repository : https://git.spboucher.ai/auto-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1214#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# Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/gatsby_dealers.py : connecteurs des concessionnaires de marque91# sur la plateforme Gatsby « autoroot.io » (inventaire EvalAuto — Groupe92# Beaucage : Kia Granby/Drummondville, Mazda Sherbrooke, Mitsubishi et93# Nissan Drummondville, Nissan Victoriaville).94#95# Même plateforme que megacentredeliquidation (voir megacentre.py) : chaque96# véhicule expose /page-data/auto-usage/<slug>/page-data.json -> `usedCar`97# complet. MAIS contrairement au Méga Centre, le sitemap de ces sites ne98# référence pas les pages véhicule individuelles — seulement les pages99# catégorie. L'énumération passe donc par l'API AWS AppSync que le site100# utilise lui-même côté client : le endpoint GraphQL et la clé x-api-key101# sont publiés dans siteParameters du page-data de la page liste102# (/page-data/auto-usage/page-data.json). La requête103# getUsedCarSearchByRelevanceMultiTable, filtrée par nameDealer, renvoie104# 30 items/page + nextFilter (curseur) -> tous les slugs.105#106# Le reste (cache hebdo des page-data détail, plafond AUTOKA_MAX_DETAILS,107# usedCar -> Vehicle) est hérité de MegaCentreDeLiquidation.108# AUTOKA_MAX_PAGES (env) limite la pagination AppSync pour les tests.109# -----------------------------------------------------------------------------110from __future__ import annotations111112import json113import os114import time115116from .megacentre import MegaCentreDeLiquidation117118_QUERY_NAME = "getUsedCarSearchByRelevanceMultiTable"119120# champs minimaux : on ne veut que les slugs (le détail vient du page-data)121_ITEM_FIELDS = "{ nextFilter items { id slug nameDealer } }"122123124class GatsbyEvalAutoConnector(MegaCentreDeLiquidation):125 """Base des sites Gatsby autoroot/EvalAuto sans sitemap véhicule."""126127 source_id = "" # base non enregistrée par le registre128 base_url = ""129 dealer_name = ""130 city = ""131 request_delay = 1.0132 max_details = 300133 max_aws_pages = 60 # garde-fou dur (60 x 30 = 1 800 véh.)134135 # -- POST GraphQL poli ----------------------------------------------------136 def _post_json(self, url: str, payload: dict, headers: dict) -> dict:137 wait = self.request_delay - (time.time() - self._last_request)138 if wait > 0:139 time.sleep(wait)140 resp = self.session.post(url, json=payload, headers=headers,141 timeout=self.timeout)142 self._last_request = time.time()143 resp.raise_for_status()144 return resp.json()145146 @staticmethod147 def _gql(dealer: str, next_item: str | None) -> str:148 nxt = f', usedCarNextItem:"{next_item}"' if next_item else ""149 return f"""150 {{151 {_QUERY_NAME}(order: "DESC",152 searchValue: "",153 maxPrice: 1000000,154 minPrice: 0,155 maxYear: 2035,156 minYear: 1900,157 brand: [],158 model: [],159 nameDealer: {json.dumps([dealer])},160 extColor: [],161 drivetrain: [],162 passengers: [],163 engine: [],164 bodytype: [],165 transmission: [],166 certified: [true,false],167 discount: [true,false],168 prestige: [true,false]169 {nxt})170 {_ITEM_FIELDS}171 }}172 """173174 # -- énumération des slugs via la page liste + AppSync ---------------------175 def _vehicle_slugs(self) -> list[str]:176 data = self.get(177 f"{self.base_url}/page-data/auto-usage/page-data.json").json()178 result = data.get("result") or {}179 params = (result.get("data") or {}).get("siteParameters") or {}180 context = result.get("pageContext") or {}181182 # les 30 premiers véhicules sont pré-rendus dans le pageContext183 slugs = {str(c.get("slug")) for c in context.get("allUsedCar") or []184 if c.get("slug")}185186 endpoint = str(params.get("awsEndpoint") or "")187 token = str(params.get("awsToken") or "")188 dealer = str(params.get("awsDealerNameFilter")189 or context.get("nameDealer") or self.dealer_name)190 if not endpoint or not token: # repli : pré-rendu seulement191 return sorted(slugs)192193 cap = min(int(os.environ.get("AUTOKA_MAX_PAGES", self.max_aws_pages)),194 self.max_aws_pages)195 headers = {"x-api-key": token, "Content-Type": "application/json"}196 next_item: str | None = None197 for _ in range(cap):198 try:199 resp = self._post_json(endpoint,200 {"query": self._gql(dealer, next_item)},201 headers)202 except Exception:203 break # AppSync HS -> pré-rendu204 payload = (resp.get("data") or {}).get(_QUERY_NAME) or {}205 items = payload.get("items") or []206 for item in items:207 slug = str(item.get("slug") or "")208 if slug:209 slugs.add(slug)210 next_item = payload.get("nextFilter")211 if not items or not next_item:212 break213 return sorted(slugs)214215 # -- usedCar -> Vehicle (ville de repli) -----------------------------------216 def _to_vehicle(self, slug, d):217 veh = super()._to_vehicle(slug, d)218 if veh is not None and not veh.city:219 veh.city = self.city220 return veh221222223# ---------------------------------------------------------------------------224# Concessionnaires (1 sous-classe = 1 source) — Groupe Beaucage225# ---------------------------------------------------------------------------226227class KiaGranby(GatsbyEvalAutoConnector):228 source_id = "kiagranby"229 base_url = "https://www.kiagranby.com"230 dealer_name = "Kia de Granby"231 city = "Granby"232233234class KiaDrummondville(GatsbyEvalAutoConnector):235 source_id = "kiadrummondville"236 base_url = "https://www.kiadrummondville.com"237 dealer_name = "Kia Drummondville"238 city = "Drummondville"239240241class MazdaDeSherbrooke(GatsbyEvalAutoConnector):242 source_id = "mazdadesherbrooke"243 base_url = "https://www.mazdadesherbrooke.com"244 dealer_name = "Mazda de Sherbrooke"245 city = "Sherbrooke"246247248class MitsubishiDrummondville(GatsbyEvalAutoConnector):249 source_id = "mitsubishidrummondville"250 base_url = "https://www.mitsubishidrummondville.com"251 dealer_name = "Mitsubishi Drummondville"252 city = "Drummondville"253254255class NissanDrummondville(GatsbyEvalAutoConnector):256 source_id = "nissandrummondville"257 base_url = "https://www.nissandrummondville.com"258 dealer_name = "Nissan Drummondville"259 city = "Drummondville"260261262class NissanVictoriaville(GatsbyEvalAutoConnector):263 source_id = "nissanvictoriaville"264 base_url = "https://www.nissanvictoriaville.com"265 dealer_name = "Nissan de Victoriaville"266 city = "Victoriaville"267