Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/liftsystem.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2713# Last Modified : 2026-08-2714#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 (Québec + expansion Ontario)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/liftsystem.py : connecteur GÉNÉRIQUE Rentsync/LiftSystem91# Des dizaines de gestionnaires (surtout en Ontario) publient leur parc via92# la même plateforme Rentsync « classique », dont le flux JSON officiel est93# `https://api.theliftsystem.com/v2/search?client_id=<N>&auth_token=<token>`.94# Le token est universel (embarqué dans le /scripts/main.js de chaque site) ;95# seul le client_id change. Plutôt que N modules copiés-collés, ce module lit96# le registre data/liftsystem_clients.json ({id, name, site, client_id…},97# découverts et validés en live le 2026-08-26) et GÉNÈRE une sous-classe de98# BaseConnector par client (source_id = "lift_<id>", ex. "lift_greenwin"),99# déposée dans les globals du module pour que le registre auto-découvrant100# (connectors/__init__.py) les enregistre toutes. Mapping identique au101# connecteur canonique centurion.py (même plateforme, client_id 21) : adresse102# complète, geocode, prix min « À partir de », galerie assets.rentsync.com103# via le cache BD self.detail() (revisitée quand la ligne du flux change).104# Différence : les flux sont pancanadiens — on ne garde que ON et QC, et le105# champ Listing.province est renseigné selon la propriété.106#107# Expansion Ontario — activer via LOUKA_ONTARIO=1108# (voir gestion-immobiliere-ontario.md) : sans la variable, toutes les109# classes générées sont `disabled` et donc exclues du registre / de la prod.110# -----------------------------------------------------------------------------111from __future__ import annotations112113import hashlib114import json115import os116import re117from pathlib import Path118119from bs4 import BeautifulSoup120121from ..schema import Listing, infer_city, normalize_unit_type122from .base import BaseConnector123124# Gate expansion Ontario : rien ne s'active en prod sans LOUKA_ONTARIO=1125_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"126127REGISTRY_PATH = Path(__file__).resolve().parents[2] / "data" / \128 "liftsystem_clients.json"129LIFT_API = "https://api.theliftsystem.com/v2/search"130131# Jeton universel Rentsync/LiftSystem — le même pour tous les sites clients132# (vérifié dans le main.js de cpliving, parkproperty, williamsandmcdaniel,133# yorkproperty… et validé sur les 13 client_id du registre le 2026-08-26).134# Une entrée du registre peut le surcharger via sa clé "auth_token".135DEFAULT_AUTH_TOKEN = "sswpREkUtyeYjeoahA2i"136137# Provinces couvertes par Lou-Ka — plusieurs clients sont pancanadiens138# (Shelter Canadian : MB/AB/SK…) : tout le reste est ignoré au fetch.139_PROVINCES = {"ON", "QC"}140141# Types de propriété NON résidentiels du flux (property_type, chaîne libre) —142# plusieurs clients mélangent bureaux/commerces (tarifs au pi², ex. « 18 $ »)143# et chantiers sans unités : hors sujet pour Lou-Ka (logements au mois).144_NON_RESIDENTIAL = {145 "office", "retail", "warehouse", "industrial", "commercial", "land",146 "construction", "motel", "hotel", "parking", "storage",147}148149# galerie de la fiche propriété (img + backgrounds CSS), comme centurion.py150_IMG_RE = re.compile(151 r"https://assets\.rentsync\.com/[^\"'\\)\s]+\.(?:jpg|jpeg|png|webp)", re.I)152_SKIP_IMG = re.compile(r"logo|icon|favicon|badge|/thumb", re.I)153154155def _load_registry() -> list[dict]:156 """Entrées validées du registre (client_id présent, status != a_verifier)."""157 try:158 data = json.loads(REGISTRY_PATH.read_text("utf-8"))159 except (OSError, ValueError):160 return []161 return [c for c in data.get("clients") or []162 if c.get("client_id") and c.get("status") == "valide"]163164165class LiftSystemConnector(BaseConnector):166 """Base commune des connecteurs LiftSystem générés — non enregistrée167 elle-même (source_id vide) ; chaque sous-classe reçoit son entrée de168 registre dans l'attribut de classe `client`."""169170 source_id = "" # les sous-classes générées le définissent171 client: dict = {} # entrée du registre (name, site, client_id…)172 request_delay = 0.7 # politesse — même rythme que centurion.py173 max_properties = 400 # garde-fou (plus gros client : ~204 propriétés)174 max_images = 20175176 def fetch(self) -> list[Listing]:177 props = self.get(LIFT_API, params={178 "client_id": str(self.client["client_id"]),179 "auth_token": self.client.get("auth_token") or DEFAULT_AUTH_TOKEN,180 "show_all_properties": "true",181 "show_custom_fields": "true",182 "show_amenities": "true",183 "show_promotions": "true",184 "limit": "1000",185 }, headers={"Accept": "application/json",186 "Referer": (self.client.get("site") or "") + "/"}).json()187188 listings: list[Listing] = []189 for p in props:190 if len(listings) >= self.max_properties: # garde-fou APRÈS filtres191 break192 try:193 addr = p.get("address") or {}194 if (addr.get("province_code") or "").upper() not in _PROVINCES:195 continue # flux pancanadiens : ON et QC seulement196 ptype = str(p.get("property_type") or "").strip().lower()197 if ptype in _NON_RESIDENTIAL:198 continue # bureaux/commerces/chantiers : hors sujet199 listings.append(self._listing(p))200 except Exception:201 continue202 return listings203204 # -- une annonce par propriété (mapping aligné sur centurion.py) -----------205 def _listing(self, p: dict) -> Listing:206 pid = str(p.get("id"))207 addr = p.get("address") or {}208 url = p.get("permalink") or self.client.get("listing_url") or \209 self.client.get("site") or ""210 # certains clients publient des permaliens cassés (ex. Shelter :211 # « /images/<slug> » → 404, la vraie fiche est « /residential-rental/ »)212 # — correctif déclaré au registre : "permalink_sub": [avant, après]213 sub = self.client.get("permalink_sub") or []214 if len(sub) == 2 and sub[0] in url:215 url = url.replace(sub[0], sub[1], 1)216 name = (p.get("name") or "").strip()217 prov = (addr.get("province_code") or "").upper()218219 # adresse complète : rue + ville + « , ON/QC <postal> » selon le flux220 city = re.sub(r"\s+(?:ON|QC)$", "",221 (addr.get("city") or "").strip(), flags=re.I)222 street = (addr.get("address") or "").strip()223 postal = (addr.get("postal_code") or "").strip()224 full_addr = ", ".join(x for x in (street, city) if x)225 if full_addr:226 full_addr += f", {prov} {postal}".rstrip()227 sector = (addr.get("neighbourhood") or "").strip()228229 # coordonnées GPS structurées du flux230 geo = p.get("geocode") or {}231 try:232 lat = float(geo["latitude"]) if geo.get("latitude") else None233 lng = float(geo["longitude"]) if geo.get("longitude") else None234 except (TypeError, ValueError):235 lat = lng = None236237 # sommaire des unités disponibles (rempli seulement s'il y a vacance)238 stats = ((p.get("statistics") or {}).get("suites") or {})239 rates = stats.get("rates") or {}240 beds = stats.get("bedrooms") or {}241 baths = stats.get("bathrooms") or {}242 sqft = stats.get("square_feet") or {}243 price = float(rates["min"]) if rates.get("min") else None244 price_label = ""245 if price is not None:246 price_label = (f"À partir de {price:.0f} $"247 if rates.get("max") and rates["max"] != rates["min"]248 else f"{price:.0f} $ /mois")249 # type d'unité : seulement si la gamme est sans ambiguïté250 unit_type = ""251 if beds.get("min") is not None and beds.get("min") == beds.get("max"):252 n = int(beds["min"])253 unit_type = "Studio" if n == 0 else normalize_unit_type(254 f"{n} chambres")255 # superficie : le flux publie parfois « 0.0 » — ignorer256 area = None257 try:258 v = float(sqft.get("min") or 0)259 if 80 <= v <= 20000:260 area = v261 except (TypeError, ValueError):262 pass263264 # disponibilité : libellé du flux (« No Vacancy », « X Vacancies »…)265 availability = (p.get("availability_status_label") or "").strip()266 avail_date = None267 mad = str(p.get("min_availability_date") or "").strip()268 if re.fullmatch(r"20\d{2}-\d{2}-\d{2}", mad[:10]):269 avail_date = mad[:10]270271 # description : aperçu HTML du flux (rendu texte)272 details_src = p.get("details") or {}273 desc = BeautifulSoup(details_src.get("overview") or "",274 "html.parser").get_text(" ", strip=True)275 promo = p.get("promotion") or {}276 promo_txt = (promo.get("title") or promo.get("name") or "").strip() \277 if isinstance(promo, dict) else ""278 if promo_txt:279 desc = f"Promotion : {promo_txt}. {desc}".strip()280281 # commodités : liste du flux + champ personnalisé Rentsync (CSV)282 amenities: list[str] = []283 for a in p.get("amenities") or []:284 t = (a.get("name") if isinstance(a, dict) else str(a) or "").strip()285 if t and t not in amenities:286 amenities.append(t)287 cf = p.get("custom_fields") or {}288 for t in (cf.get("amenities") or "").split(","):289 t = t.strip()290 if t and t not in amenities:291 amenities.append(t)292293 # champs structurés du flux294 details: dict = {}295 contact = p.get("contact") or {}296 if contact.get("phone"):297 details["contact"] = {"phone": contact["phone"]}298 if contact.get("email"):299 details.setdefault("contact", {})["email"] = contact["email"]300 # pet_friendly=false ne distingue pas « interdit » de « non renseigné »301 pets = "oui" if p.get("pet_friendly") is True else None302303 # galerie photo de la fiche propriété — via le cache BD : revisitée304 # seulement quand la ligne du flux change305 feed_key = hashlib.sha1("|".join(str(x) for x in (306 p.get("availability_count"), p.get("availability_status"),307 rates.get("min"), rates.get("max"), mad, p.get("photo"),308 )).encode("utf-8")).hexdigest()309 d = self.detail(pid, feed_key, lambda: self._fetch_gallery(url))310 images = list(d.get("images") or [])311 photo = (p.get("photo_path") or "").strip()312 if photo and photo not in images:313 images.insert(0, photo)314315 # infer_city (secteur -> Lévis…) n'a de sens que côté Québec316 final_city = infer_city(sector, default=city) if prov == "QC" else city317318 return Listing(319 source=self.source_id,320 external_id=pid,321 url=url,322 title=name,323 address=full_addr,324 sector=sector,325 city=final_city,326 province=prov,327 unit_type=unit_type,328 price=price,329 price_label=price_label,330 availability=availability,331 availability_date=avail_date,332 area_sqft=area,333 pets=pets,334 description=desc[:600] + (335 f" Salles de bain : {baths['min']:g}+."336 if baths.get("min") else ""),337 amenities=amenities[:25],338 details=details,339 images=images[: self.max_images],340 lat=lat,341 lng=lng,342 )343344 def _fetch_gallery(self, url: str) -> dict:345 """Scrape la galerie photo (assets.rentsync.com) de la fiche propriété."""346 out: dict = {"images": []}347 if not url:348 return out349 try:350 page = self.get(url).text351 except Exception:352 return out353 images: list[str] = []354 for u in _IMG_RE.findall(page):355 if _SKIP_IMG.search(u):356 continue357 # variante pleine résolution de la galerie (…/gallery/full/…)358 u = re.sub(r"/gallery/\d{3,4}/", "/gallery/full/", u)359 if u not in images:360 images.append(u)361 out["images"] = images[: self.max_images]362 return out363364365# -----------------------------------------------------------------------------366# Génération : une sous-classe par client du registre, déposée dans les globals367# du module — connectors/__init__.py (scan de vars(module)) les découvre alors368# comme n'importe quel connecteur écrit à la main.369# -----------------------------------------------------------------------------370def _make_connector(entry: dict) -> type[LiftSystemConnector]:371 cls = type(372 f"Lift{re.sub(r'[^A-Za-z0-9]', '', entry['id']).capitalize()}Connector",373 (LiftSystemConnector,),374 {375 "source_id": f"lift_{entry['id']}",376 "client": entry,377 # Expansion Ontario — activer via LOUKA_ONTARIO=1378 # (voir gestion-immobiliere-ontario.md)379 "disabled": not _ONTARIO,380 "__doc__": f"Connecteur LiftSystem généré — {entry.get('name')} "381 f"(client_id {entry.get('client_id')}).",382 },383 )384 return cls385386387def _register_all() -> None:388 for entry in _load_registry():389 cls = _make_connector(entry)390 globals()[cls.__name__] = cls391392393_register_all()394