Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/gestion_cem.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-09-1714#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/gestion_cem.py : Gestion CEM (gestioncem.com — Montréal, Longueuil,91# LaSalle/Sud-Ouest…) via son portail Eversa (gestioncem.eversa.app).92# Techno : React Router v7 (Remix) « turbo-stream » — les routes exposent un93# endpoint JSON `<route>.data` contenant un TABLEAU PLAT à références94# indexées : {"_1":2} = clé à l'index 1, valeur à l'index 2 ; entier négatif95# = null/undefined ; ["D", <millis>] = date epoch. On décode récursivement.96# Granularité : UNITÉ (page détail par immeuble -> units[] avec listed=true,97# prix, pi², chambres, sdb, photos, date de disponibilité). Repli sur la98# carte de l'immeuble si la page détail est indisponible (404 transitoire).99# Depuis ~2026-09-17 les routes exigent un préfixe de locale (/fr, /en) :100# sans préfixe, `.data` renvoie un SingleFetchRedirect 301 (payload liste).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import datetime105import json106import re107108import requests109110from .base import BaseConnector111from ..schema import Listing112113BASE = "https://gestioncem.eversa.app"114115# chunks turbo-stream inlinés dans le HTML (repli quand `.data` renvoie 404)116_ENQUEUE_RE = re.compile(r'streamController\.enqueue\((".*?")\);', re.S)117118119def _decode(raw: str):120 """Décode un document turbo-stream (tableau plat à références indexées)."""121 # Depuis ~2026-08-23 le flux ajoute des lignes différées (`P14:[…]`, promesses122 # résolues — ex. walkscore) après le document principal : ne garder que la123 # 1re ligne, sinon json.loads échoue en « Extra data ».124 arr = json.loads(raw.split("\n", 1)[0])125 memo: dict = {}126127 def dec(i):128 if isinstance(i, int) and i < 0: # codes spéciaux (null/undefined…)129 return None130 if not isinstance(i, int) or i >= len(arr):131 return i132 if i in memo:133 return memo[i]134 v = arr[i]135 if isinstance(v, dict):136 out: dict = {}137 memo[i] = out138 for k, val in v.items():139 key = dec(int(k[1:])) if k.startswith("_") else k140 out[key] = dec(val) if isinstance(val, int) else val141 return out142 if isinstance(v, list):143 # ["D", <epoch millis>] = date sérialisée (le millis est LITTÉRAL,144 # pas une référence — souvent hors du tableau)145 if len(v) == 2 and v[0] == "D" and isinstance(v[1], (int, float)):146 iso = datetime.datetime.fromtimestamp(147 v[1] / 1000, tz=datetime.timezone.utc).date().isoformat()148 memo[i] = iso149 return iso150 out2: list = []151 memo[i] = out2152 for e in v:153 out2.append(dec(e) if isinstance(e, int) else e)154 return out2155 memo[i] = v156 return v157158 return dec(0)159160161def _num(v) -> float | None:162 """'1695' / 1695 / '2 000' -> float (None si vide/0)."""163 if isinstance(v, (int, float)):164 return float(v) if v > 0 else None165 if isinstance(v, str):166 s = v.replace(" ", "").replace(" ", "").replace(",", ".")167 try:168 f = float(s)169 return f if f > 0 else None170 except ValueError:171 return None172 return None173174175def _unit_type(bedrooms) -> str:176 """Chambres -> typologie QC (0 ch = studio, n ch = (n+2)½)."""177 try:178 bd = int(float(bedrooms))179 except (TypeError, ValueError):180 return ""181 if bd <= 0:182 return "Studio"183 if bd >= 5:184 return "6½+"185 return f"{bd + 2}½"186187188def _images(items, uid: str = "") -> list[str]:189 out: list[str] = []190 for i in items or []:191 if not isinstance(i, str) or not i:192 continue193 url = i if i.startswith("http") else BASE + i194 if url not in out:195 out.append(url)196 return out197198199class GestionCemConnector(BaseConnector):200 """Gestion CEM via Eversa — annonces à l'unité (repli : immeuble)."""201202 source_id = "gestion_cem"203 request_delay = 0.8204205 # -- helpers ---------------------------------------------------------------206 def _route_data(self, path: str):207 """Décode `<path>.data` ; repli sur les chunks inlinés du HTML."""208 try:209 resp = self.get(f"{BASE}{path}.data")210 resp.encoding = "utf-8" # turbo-stream sans charset déclaré211 return _decode(resp.text)212 except requests.HTTPError:213 pass214 resp = self.get(f"{BASE}{path}")215 resp.encoding = "utf-8"216 chunks = _ENQUEUE_RE.findall(resp.text)217 if not chunks:218 return None219 raw = "".join(json.loads(c) for c in chunks)220 payload = _decode(raw)221 # le HTML enveloppe la même donnée sous loaderData222 if isinstance(payload, dict) and "loaderData" in payload:223 return payload["loaderData"]224 return payload225226 def _detail_listing(self, slug: str) -> dict | None:227 data = self._route_data(f"/fr/listings/{slug}/details")228 if not isinstance(data, dict):229 return None230 page = data.get("PublicListingDetailPage") or {}231 if "data" in page:232 page = page.get("data") or {}233 listing = page.get("listing")234 return listing if isinstance(listing, dict) else None235236 def _building_fallback(self, b: dict, page_url: str) -> Listing | None:237 """Carte de la liste -> une annonce « immeuble » (détail indisponible)."""238 price = _num(b.get("minPricePerMonth") or b.get("price"))239 bd = b.get("bedrooms")240 avail = str(b.get("availability") or "")[:10]241 return Listing(242 source=self.source_id,243 external_id=b.get("slug") or b.get("listingId") or "",244 url=page_url,245 title=(b.get("title") or b.get("street") or "").strip(),246 address=(b.get("street") or "").strip(),247 city=(b.get("city") or "").strip(),248 unit_type=_unit_type(bd),249 bedrooms=_num(bd),250 bathrooms=_num(b.get("bathrooms")),251 price=price,252 price_label=f"{price:.0f} $ /mois" if price else "",253 availability=f"Disponible le {avail}" if avail else "Disponible",254 availability_date=avail or None,255 images=_images(b.get("images") or b.get("buildingImages")),256 lat=b.get("latitude"),257 lng=b.get("longitude"),258 )259260 # -- contrat ---------------------------------------------------------------261 def fetch(self) -> list[Listing]:262 data = self._route_data("/fr/listings/list")263 page = (data or {}).get("PublicListingsLayoutPage") or {}264 if "data" in page:265 page = page.get("data") or {}266 buildings = page.get("listings") or []267268 out: list[Listing] = []269 seen: set[str] = set()270 for b in buildings:271 if not isinstance(b, dict):272 continue273 if b.get("isFullyBooked") or b.get("isAllCommercial"):274 continue275 if (b.get("spaceType") or "apartment") not in ("apartment", "condo",276 "house", "loft"):277 continue # résidentiel au mois seulement278 slug = b.get("slug") or ""279 if not slug:280 continue281 page_url = f"{BASE}/fr/listings/{slug}/details"282283 # détail (cache BD : clé = contenu de la carte liste)284 key = json.dumps({k: b.get(k) for k in285 ("price", "availability", "listedUnitCount",286 "bedrooms", "isFullyBooked")},287 sort_keys=True, default=str)288 try:289 detail = self.detail(slug, key,290 lambda s=slug: self._detail_listing(s) or {})291 except requests.RequestException:292 detail = {}293294 units = [u for u in (detail.get("units") or [])295 if isinstance(u, dict) and u.get("listed")]296 if not units: # détail 404/vide -> carte liste297 lst = self._building_fallback(b, page_url)298 if lst and lst.external_id and lst.external_id not in seen:299 seen.add(lst.external_id)300 out.append(lst)301 continue302303 street = (detail.get("street") or b.get("street") or "").strip()304 city = (detail.get("city") or b.get("city") or "").strip()305 lat = detail.get("latitude") or b.get("latitude")306 lng = detail.get("longitude") or b.get("longitude")307 bldg_imgs = _images(b.get("images") or b.get("buildingImages"))308309 for u in units:310 uid = u.get("slug") or "" # uuid stable de l'unité311 if not uid or uid in seen:312 continue313 seen.add(uid)314 price = _num(u.get("price"))315 avail = str(u.get("availability") or "")[:10]316 alias = str(u.get("alias") or "").strip()317 imgs = _images(u.get("images")) or bldg_imgs318 details: dict = {}319 if u.get("floor") is not None:320 details["floor"] = u["floor"]321 if alias:322 details["unit_number"] = alias323 out.append(Listing(324 source=self.source_id,325 external_id=uid,326 url=page_url,327 title=f"{street} — app. {alias}" if alias else street,328 address=street,329 city=city,330 unit_type=_unit_type(u.get("bedrooms")),331 bedrooms=_num(u.get("bedrooms")),332 bathrooms=_num(u.get("bathrooms")),333 price=price,334 price_label=f"{price:.0f} $ /mois" if price else "",335 availability=(f"Disponible le {avail}" if avail336 else "Disponible"),337 availability_date=avail or None,338 area_sqft=_num(u.get("area")),339 details=details,340 images=imgs[:30],341 lat=lat,342 lng=lng,343 ))344 return out345