SPB Git

Repository Public

via_capitale_agences.py 7.1 KB 180 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/via_capitale_agences.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1814#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/via_capitale_agences.py : Via Capitale par SOUS-AGENCES (robuste)91#92#   Le portail central viacapitalevendu.com est derrière Cloudflare (scrape93#   fragile, 1 page). Les sous-agences Via Capitale (Élite, Sélect, du Mont-Royal,94#   Accès…) tournent chacune sur la plateforme source.immo (plugin WordPress),95#   dont l'API publique (api-v1.source.immo) est stable et paginée — même96#   mécanique que Vendirect (voir sourceimmo.py). On génère une classe par97#   sous-agence depuis data/via_capitale_agencies.json ; le n° Centris98#   (ref_number) sert de clé de déduplication (voir web.py, sources « %_ag_% »).99#100#   La config publique de chaque site est à101#   /wp-content/uploads/_sourceimmo/_configs.json (account_id/api_key/app_id +102#   default_view). Le registre est régénérable par scripts/refresh_via_capitale.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import json107import re108from pathlib import Path109110from .sourceimmo import SourceImmoConnector111from ..schema import PropertyListing112113REGISTRY = Path(__file__).resolve().parent.parent.parent / "data" / "via_capitale_agencies.json"114115116class ViaCapitaleAgenceConnector(SourceImmoConnector):117    """Sous-agence Via Capitale sur source.immo. Les sous-classes fournissent118    account_id / api_key / app_id / view_id / site_url / agency_name."""119120    agency_name = "Via Capitale"121122    def fetch(self) -> list[PropertyListing]:123        # auto-guérison : recharger les identifiants depuis la config publique124        # du site (résilient si source.immo fait tourner ses UUID).125        try:126            cfg = self.get(127                f"{self.site_url.rstrip('/')}/wp-content/uploads/_sourceimmo/_configs.json"128            ).json()129            self.account_id = cfg.get("account_id", self.account_id)130            self.api_key = cfg.get("api_key", self.api_key)131            self.app_id = cfg.get("app_id", self.app_id)132            self.view_id = cfg.get("default_view", self.view_id)133        except Exception:134            pass                      # on garde les valeurs du registre135        return super().fetch()136137    def _to_listing(self, it: dict) -> PropertyListing | None:138        lst = super()._to_listing(it)139        if lst is not None:140            lst.broker_name = self.agency_name141            # URL lisible vers la fiche de la sous-agence quand le slug est dispo142            ref = it.get("ref_number") or it.get("id")143            if ref and self.site_url:144                lst.url = f"{self.site_url.rstrip('/')}/propriete/{ref}"145        return lst146147148def _load() -> list[dict]:149    try:150        return json.loads(REGISTRY.read_text(encoding="utf-8"))151    except Exception:152        return []153154155def _slug(banner: str) -> str:156    return "via_ag_" + re.sub(r"[^a-z0-9]+", "_", banner.lower()).strip("_")157158159# `"disabled": true` dans le registre = agence sans inventaire/doublon (voir "note")160for _ag in _load():161    if _ag.get("disabled"):162        continue163    if not all(_ag.get(k) for k in ("domain", "account", "api", "app", "view")):164        continue165    _sid = _slug(_ag["banner"])166    _name = "Via Capitale " + _ag["banner"].replace("-", " ").title()167    globals()[_sid.upper()] = type(168        "".join(p.title() for p in _sid.split("_")),169        (ViaCapitaleAgenceConnector,),170        {171            "source_id": _sid,172            "account_id": _ag["account"],173            "api_key": _ag["api"],174            "app_id": _ag["app"],175            "view_id": _ag["view"],176            "site_url": f"https://{_ag['domain']}",177            "agency_name": _name,178        },179    )180
Files main
Menu

Theme