SPB Git

Repository Public

tri_logis.py 13.5 KB 326 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/tri_logis.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-2314#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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/tri_logis.py : connecteur Société immobilière Tri-Logis inc.91#   (trilogis.ca — Rouyn-Noranda, 600+ logements, référence n°1 en92#   Abitibi-Témiscamingue). Réécrit 2026-08-23 : l'ancien site statique93#   tri-logis.ca (/espaces-a-louer/logements) a migré vers trilogis.ca94#   (301) — Next.js App Router (Vercel) + Supabase (projet95#   tcrymlwdnwmfmpnkrfeu.supabase.co, bucket privé property-media).96#   Méthode : la liste /a-louer est rendue serveur ; le payload RSC embarqué97#   dans le HTML (segments self.__next_f.push) contient le tableau JSON98#   `"units":[…]` complet des unités actuellement à louer — unit_id (UUID),99#   unit_name (slug de la fiche = minuscules), unit_type (residential /100#   commercial), building_address, status (vacant / departure_planned),101#   available_date, monthly_rent, rooms_notation (« 4 ½ »), bedrooms102#   (cohérent : n½ -> n-2), square_feet, sector, latitude/longitude,103#   cover_photo_url et le dict inclusions (heating/electricity/… =104#   landlord|tenant|na ; parking/laundry/furnished/balcony/pets = bool).105#   Fiche /a-louer/<slug> (RSC aussi) : galerie complète `"photos":[…]`.106#   ⚠ Les URLs d'images sont SIGNÉES (bucket privé, token ~7 jours, l'accès107#   public renvoie 400) : elles sont re-signées à chaque rendu, donc on108#   rafraîchit la galerie à chaque sync (clé de cache = iat du token de la109#   couverture) plutôt que de servir des liens expirés. La clé anon Supabase110#   n'est PAS exposée dans les chunks JS (tout est rendu serveur) : l'API111#   REST /rest/v1 n'est donc pas utilisable — le RSC est la voie robuste.112#   Périmètre : logements résidentiels longue durée seulement (unit_type113#   == "residential") ; les locaux commerciaux du même payload sont exclus,114#   comme l'étaient /studios et /chalets sur l'ancien site.115# -----------------------------------------------------------------------------116from __future__ import annotations117118import hashlib119import json120import re121122from ..schema import Listing, normalize_unit_type123from .base import BaseConnector124125BASE = "https://trilogis.ca"126LIST_URL = f"{BASE}/a-louer"127128# segments RSC injectés par Next.js dans le HTML rendu serveur129_PUSH_RE = re.compile(r'self\.__next_f\.push\(\[1,\s*"(.*?)"\]\)', re.S)130# iat du token de signature Supabase (change à chaque rendu de la page)131_IAT_RE = re.compile(r'"iat":(\d+)')132133# inclusions « landlord » (payées par le proprio) -> libellé affichable134_INCL_LANDLORD = {135    "heating": "Chauffage inclus",136    "electricity": "Électricité incluse",137    "water": "Eau incluse",138    "hot_water": "Eau chaude incluse",139    "internet": "Internet inclus",140    "snow_entrance": "Déneigement de l'entrée inclus",141    "snow_parking": "Déneigement du stationnement inclus",142}143# inclusions booléennes -> commodité144_INCL_BOOL = {145    "parking": "Stationnement",146    "laundry": "Buanderie",147    "balcony": "Balcon",148}149# statuts observés -> texte de disponibilité150_STATUS_FR = {151    "vacant": "Disponible dès maintenant",152    "departure_planned": "Bientôt disponible",153}154155156def _rsc_blob(html: str) -> str:157    """Reconstitue le flux RSC (React Server Components) embarqué dans le HTML.158159    Les segments sont des chaînes JS échappées façon JSON ; on les décode via160    json.loads pour restituer les \\uXXXX et \\" avant de les concaténer.161    """162    parts: list[str] = []163    for raw in _PUSH_RE.findall(html):164        try:165            parts.append(json.loads(f'"{raw}"'))166        except ValueError:167            parts.append(raw)          # segment atypique : garder brut168    return "".join(parts)169170171def _extract_array(blob: str, key: str) -> list | None:172    """Extrait le tableau JSON qui suit `"<key>":` dans le flux RSC."""173    i = blob.find(f'"{key}":')174    if i < 0:175        return None176    try:177        value, _ = json.JSONDecoder().raw_decode(blob, i + len(key) + 3)178    except ValueError:179        return None180    return value if isinstance(value, list) else None181182183class TriLogisConnector(BaseConnector):184    source_id = "tri_logis"185    request_delay = 0.6186    max_details = 60     # garde-fou fiches unité (vraies requêtes par sync)187188    def fetch(self) -> list[Listing]:189        html = self.get(LIST_URL).text190        blob = _rsc_blob(html)191        units = _extract_array(blob, "units")192        if units is None:193            # marqueur absent = structure du site changée (≠ 0 disponibilité,194            # où "units":[] serait présent) -> échec franc plutôt que found=0195            raise RuntimeError("payload RSC sans tableau \"units\" — "196                               "structure trilogis.ca/a-louer changée ?")197198        # les tokens de signature sont régénérés à chaque rendu : leur iat199        # sert de sel de cache pour re-signer la galerie à chaque sync200        m = _IAT_RE.search(blob)201        render_iat = m.group(1) if m else ""202203        self._fetched = 0204        listings: dict[str, Listing] = {}205        for u in units:206            try:207                lst = self._parse_unit(u, render_iat)208            except Exception:209                continue210            if lst is not None and lst.external_id not in listings:211                listings[lst.external_id] = lst212        return list(listings.values())213214    # -- unité (objet JSON du payload liste) -------------------------------------215    def _parse_unit(self, u: dict, render_iat: str) -> Listing | None:216        if (u.get("unit_type") or "") != "residential":217            return None                      # locaux commerciaux exclus218        ext_id = str(u.get("unit_id") or "").strip()219        unit_name = str(u.get("unit_name") or "").strip()220        if not ext_id or not unit_name:221            return None222223        slug = unit_name.lower()             # ex. 60-12_Perreault-E -> fiche224        url = f"{BASE}/a-louer/{slug}"225226        address = str(u.get("building_address") or "").strip()227        # « 58-60 Perreault-E, Rouyn-Noranda » -> ville après la virgule228        city = "Rouyn-Noranda"229        if "," in address:230            tail = address.rsplit(",", 1)[1].strip()231            if tail:232                city = tail233234        rooms = str(u.get("rooms_notation") or "").strip()235        status = str(u.get("status") or "").strip()236        avail_date = str(u.get("available_date") or "").strip()237        if status == "vacant":238            availability = _STATUS_FR["vacant"]239            availability_date = "now"240        elif avail_date:241            availability = f"Disponible le {avail_date}"242            availability_date = avail_date243        else:244            availability = _STATUS_FR.get(status, "")245            availability_date = None246247        price = u.get("monthly_rent")248        price = float(price) if isinstance(price, (int, float)) else None249        price_label = f"{price:.0f} $ / mois" if price else ""250251        # inclusions -> commodités affichables + animaux/meublé252        incl = u.get("inclusions") or {}253        amenities: list[str] = []254        for k, label in _INCL_LANDLORD.items():255            if incl.get(k) == "landlord":256                amenities.append(label)257        for k, label in _INCL_BOOL.items():258            if incl.get(k) is True:259                amenities.append(label)260        pets = None261        if isinstance(incl.get("pets"), bool):262            pets = "oui" if incl["pets"] else "non"263        furnished = incl.get("furnished") if isinstance(264            incl.get("furnished"), bool) else None265266        bedrooms = u.get("bedrooms")267        bedrooms = float(bedrooms) if isinstance(bedrooms, (int, float)) else None268269        sqft = u.get("square_feet")270        sqft = float(sqft) if isinstance(sqft, (int, float)) and sqft > 0 else None271272        images = [u["cover_photo_url"]] if str(273            u.get("cover_photo_url") or "").startswith("http") else []274275        lst = Listing(276            source=self.source_id,277            external_id=ext_id,278            url=url,279            title=f"{rooms or 'Logement'} — {address.split(',')[0].strip()}",280            address=address,281            sector=str(u.get("sector") or "").strip(),282            city=city,283            unit_type=normalize_unit_type(rooms),284            bedrooms=bedrooms,285            price=price,286            price_label=price_label,287            availability=availability,288            availability_date=availability_date,289            area_sqft=sqft,290            pets=pets,291            furnished=furnished,292            description=str(u.get("description_publique") or "").strip()[:1500],293            amenities=amenities,294            details={"building": str(u.get("building_name") or ""),295                     "status": status},296            images=images,297            lat=u.get("latitude") if isinstance(u.get("latitude"), float) else None,298            lng=u.get("longitude") if isinstance(u.get("longitude"), float) else None,299        )300301        # galerie complète via la fiche — la clé inclut l'iat du rendu : les302        # URLs signées expirent (~7 j), on les re-signe donc à chaque sync303        if (u.get("photo_count") or 0) > 1:304            key = hashlib.sha1(305                f"{price_label}|{availability}|{u.get('photo_count')}|{render_iat}"306                .encode("utf-8")).hexdigest()307            try:308                payload = self.detail(ext_id, key,309                                      lambda s=slug: self._fetch_detail(s))310                if payload.get("images"):311                    lst.images = payload["images"]312            except Exception:313                pass314        return lst315316    # -- fiche unité (/a-louer/<slug>) : galerie signée complète -----------------317    def _fetch_detail(self, slug: str) -> dict:318        if self._fetched >= self.max_details:319            raise RuntimeError("budget de fiches unité atteint")320        self._fetched += 1321        blob = _rsc_blob(self.get(f"{BASE}/a-louer/{slug}").text)322        photos = _extract_array(blob, "photos") or []323        images = [p["url"] for p in photos324                  if isinstance(p, dict) and str(p.get("url") or "").startswith("http")]325        return {"images": list(dict.fromkeys(images))[:25]}326
Files main
Menu

Theme