Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/louer_ca.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-1713# 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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/louer_ca.py : Louer.ca — portail locatif 100 % Québec du réseau91# Rentals.ca. Accès par l'API GraphQL interne (https://louer.ca/graphql),92# rétro-conçue : clé publique `rentalsGqlKey` lue dans window.appconf de la93# page d'accueil, mutation `acquireAuthInfo` -> JWT (scalaire JSON contenant94# accessToken ~1 h + refreshToken), en-tête `Authorization: Bearer <access>`.95# La recherche passe par la ville : typeahead -> City.id, puis96# `node(id){... on City{ rentalListings(first,after) }}` (curseur Relay ;97# le champ rentalListings top-level renvoie 0). Le détail `node(id)` fournit98# adresse, description, galerie (images.rentals.ca) et les floorPlans99# (un type/prix par plan) -> une annonce Lou-Ka par plan d'étage.100# ⚠️ Réseau Rentals.ca : CGU interdisant l'extraction sans accord écrit.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import base64105import datetime106import json107import os108import re109import time110111from ..schema import Listing112from .base import BaseConnector113from . import _detailutil as du114115HOME = "https://louer.ca/"116GQL = "https://louer.ca/graphql"117FALLBACK_KEY = "ME8N-J3IX-At86-2yIi"118119# villes québécoises visées (slug interne Louer.ca) ; résolues via typeahead120CITIES = ["montreal", "quebec", "laval", "gatineau", "longueuil", "sherbrooke",121 "trois-rivieres", "levis", "terrebonne", "brossard", "saguenay",122 "drummondville", "granby", "saint-jean-sur-richelieu", "repentigny"]123124PAGE_SIZE = int(os.environ.get("LOUKA_LOUERCA_PAGE_SIZE", "50"))125DETAIL_LIMIT = int(os.environ.get("LOUKA_LOUERCA_DETAIL_LIMIT", "600"))126TTL_DAYS = float(os.environ.get("LOUKA_LOUERCA_TTL_DAYS", "5"))127MAX_PER_CITY = int(os.environ.get("LOUKA_LOUERCA_MAX_PER_CITY", "0")) # 0 = tout128129# amenity (catégorie, valeur) -> libellé FR affichable130_AMENITY_FR = {131 "laundry-facilities": "Buanderie", "in-suite-laundry": "Laveuse/sécheuse dans l'unité",132 "security-on-site": "Sécurité sur place", "storage-lockers": "Espace de rangement",133 "swimming-pool": "Piscine", "gym": "Salle d'entraînement", "elevator": "Ascenseur",134 "sauna": "Sauna", "on-site-staff": "Personnel sur place", "stove": "Cuisinière",135 "fridge": "Réfrigérateur", "balcony": "Balcon", "microwave": "Micro-ondes",136 "dishwasher": "Lave-vaisselle", "air-conditioning": "Air climatisé",137 "individual-thermostats": "Thermostats individuels", "heating": "Chauffage inclus",138 "water": "Eau incluse", "hydro-electricity": "Électricité incluse",139 "public-transit": "Transport en commun à proximité", "parking": "Stationnement",140 "no-smoking-allowed": "Non-fumeur",141}142143144class LouerCaConnector(BaseConnector):145 source_id = "louer_ca"146 request_delay = 0.5147 # points d'entrée du réseau Rentals.ca — surchargés par rentals_ca.py148 home_url = HOME149 gql_url = GQL150 site = "https://louer.ca"151 fallback_key = FALLBACK_KEY152 page_size = PAGE_SIZE153 max_per_city = MAX_PER_CITY154155 def __init__(self) -> None:156 super().__init__()157 self.session.headers.update({158 "Content-Type": "application/json",159 "Origin": self.site,160 "Referer": self.home_url,161 })162 self._token = ""163 self._token_time = 0.0164 self._api_key = self.fallback_key165166 # -- auth ------------------------------------------------------------------167 def _ensure_token(self) -> None:168 if self._token and time.time() - self._token_time < 2700: # ~45 min169 return170 try:171 home = self.get(self.home_url).text172 m = re.search(r'"rentalsGqlKey":\s*"([^"]+)"', home)173 if m:174 self._api_key = m.group(1)175 except Exception:176 pass177 data = self._gql(178 "mutation($k:String!){acquireAuthInfo(credentials:{apiKey:$k}){jwt status}}",179 {"k": self._api_key}, auth=False)180 auth = (data or {}).get("acquireAuthInfo") or {}181 jwt = auth.get("jwt")182 if isinstance(jwt, str) and jwt.startswith("{"):183 jwt = json.loads(jwt)184 token = jwt.get("accessToken") if isinstance(jwt, dict) else jwt185 if not token:186 raise RuntimeError("Louer.ca: handshake JWT échoué")187 self._token = token188 self._token_time = time.time()189190 def _gql(self, query: str, variables: dict, auth: bool = True) -> dict:191 headers = {}192 if auth:193 self._ensure_token()194 headers["Authorization"] = f"Bearer {self._token}"195 resp = self.post(self.gql_url, data=json.dumps({"query": query,196 "variables": variables}),197 headers=headers)198 payload = resp.json()199 if payload.get("errors"):200 msg = payload["errors"][0].get("message", "")201 if "AUTH" in msg.upper() and auth: # jeton expiré : on réessaie202 self._token = ""203 self._ensure_token()204 resp = self.post(self.gql_url,205 data=json.dumps({"query": query,206 "variables": variables}),207 headers={"Authorization": f"Bearer {self._token}"})208 payload = resp.json()209 return payload.get("data") or {}210211 # -- découverte ------------------------------------------------------------212 def _city_id(self, slug: str) -> str | None:213 d = self._gql(214 "query($v:String!){typeahead(value:$v){nodeType node{id ... on City"215 "{name path regionCode listingCount}}}}", {"v": slug.replace("-", " ")})216 for it in d.get("typeahead") or []:217 node = it.get("node") or {}218 if node.get("path") == slug and node.get("regionCode") == "QC":219 return node.get("id")220 # à défaut, première ville québécoise proposée221 for it in d.get("typeahead") or []:222 node = it.get("node") or {}223 if node.get("id") and node.get("regionCode") == "QC":224 return node.get("id")225 return None226227 _LIST_FRAG = ("id name path location rentRange bedsRange bathsRange "228 "sizeRange type furnished petOptions amenities verified "229 "created modified")230231 def _city_listings(self, city_id: str) -> list[dict]:232 query = ("query($id:ID!,$first:PositiveInt!,$after:String){node(id:$id)"233 "{... on City{rentalListings(first:$first,after:$after){"234 "meta{totalCount} pageInfo{hasNextPage endCursor} "235 "edges{node{" + self._LIST_FRAG + "}}}}}}")236 out, after = [], None237 while True:238 d = self._gql(query, {"id": city_id, "first": self.page_size,239 "after": after})240 rl = ((d.get("node") or {}).get("rentalListings")) or {}241 edges = rl.get("edges") or []242 out.extend(e["node"] for e in edges if e.get("node"))243 info = rl.get("pageInfo") or {}244 if not info.get("hasNextPage") or not edges:245 break246 if self.max_per_city and len(out) >= self.max_per_city:247 break248 after = info.get("endCursor")249 return out250251 _DETAIL_FRAG = ("id name path location "252 "address{city{name regionCode} neighbourhood{name} "253 "postalCode street} description{plain} "254 "imagesCount images{scales} tours{name type refId} "255 "floorPlans{beds baths rent size availability furnished "256 "tours{name type refId}}")257258 def _detail(self, gid: str) -> dict:259 d = self._gql("query($id:ID!){node(id:$id){... on RentalListing{"260 + self._DETAIL_FRAG + "}}}", {"id": gid})261 return d.get("node") or {}262263 # -- construction ----------------------------------------------------------264 @staticmethod265 def _unit_type(beds) -> str:266 try:267 b = float(beds)268 except (TypeError, ValueError):269 return ""270 if b <= 0:271 return "Studio"272 n = int(b) + 2 # chambres -> pièces et demie273 return "6½+" if n >= 6 else f"{n}½"274275 @staticmethod276 def _amenities(pairs) -> list[str]:277 out = []278 for pair in pairs or []:279 val = pair[1] if isinstance(pair, list) and len(pair) > 1 else None280 label = _AMENITY_FR.get(val)281 if label and label not in out:282 out.append(label)283 return out284285 def _images(self, node: dict) -> list[str]:286 imgs = []287 for im in node.get("images") or []:288 scales = im.get("scales")289 if isinstance(scales, str):290 try:291 scales = json.loads(scales)292 except ValueError:293 scales = []294 best = ""295 for sc in scales or []:296 if sc.get("name") in ("large", "medium") and sc.get("url"):297 best = sc["url"]298 if sc["name"] == "large":299 break300 if not best and scales:301 best = scales[0].get("url", "")302 if best and best not in imgs:303 imgs.append(best)304 return imgs305306 @staticmethod307 def _count(v) -> float | None:308 """beds/baths GraphQL -> float (0 = studio) ; None si inconnu."""309 try:310 f = float(v)311 except (TypeError, ValueError):312 return None313 return f if 0 <= f <= 20 else None314315 @staticmethod316 def _tour_url(tours) -> str | None:317 """URL de visite virtuelle depuis les `tours` GraphQL du réseau318 Rentals.ca : refId Matterport/YouTube (ou URL complète). La visite319 interactive prime sur la simple vidéo."""320 video = None321 for t in tours or []:322 ref = str(t.get("refId") or "").strip()323 typ = t.get("type") or ""324 if not ref:325 continue326 if ref.startswith("http"):327 url = ref328 elif "matterport" in typ:329 url = f"https://my.matterport.com/show/?m={ref}"330 elif "youtube" in typ:331 url = f"https://www.youtube.com/watch?v={ref}"332 else:333 continue334 if "interactive" in typ or "matterport" in typ:335 return url336 video = video or url337 return video338339 @staticmethod340 def _numeric_id(gid: str) -> str:341 """« cmVudGFsbGlzdGluZzoxMTMyMTE2 » -> « 1132116 » (rentallisting:1132116)."""342 try:343 decoded = base64.b64decode(gid + "==").decode("utf-8", "ignore")344 m = re.search(r"(\d+)", decoded)345 if m:346 return m.group(1)347 except Exception:348 pass349 m = re.search(r"(\d+)", gid)350 return m.group(1) if m else gid351352 def _card_listings(self, card: dict, node: dict, today: str,353 default_city: str = "") -> list[Listing]:354 """Annonces Lou-Ka d'une carte liste + son nœud détail GraphQL355 (une par plan d'étage). Partagé avec rentals_ca.py."""356 out: list[Listing] = []357 gid = card.get("id")358 addr = node.get("address") or {}359 city = (addr.get("city") or {}).get("name") or default_city360 sector = (addr.get("neighbourhood") or {}).get("name") or ""361 loc = card.get("location") or []362 lng, lat = (loc + [None, None])[:2]363 base_desc = ((node.get("description") or {}).get("plain")364 or "")[:6000]365 images = self._images(node)366 amenities = self._amenities(card.get("amenities"))367 common = dict(368 source=self.source_id, url=f"{self.site}/{card.get('path','')}",369 address=addr.get("street") or "", sector=sector, city=city,370 description=base_desc, amenities=amenities, images=images,371 lat=lat, lng=lng,372 )373 base_details: dict = {}374 if addr.get("postalCode"):375 base_details["Code postal"] = addr["postalCode"]376 tour = self._tour_url(node.get("tours"))377 if tour:378 base_details["virtual_tour"] = tour379 if base_details:380 common["details"] = base_details381382 plans = node.get("floorPlans") or []383 if not plans:384 # pas de plan détaillé : une annonce « à partir de »385 rng = card.get("rentRange") or []386 price = rng[0] if rng else None387 beds = (card.get("bedsRange") or [None])[0]388 lst = self._mk(common, gid, "", price,389 self._unit_type(beds), None, today,390 price_from=bool(rng))391 lst.bedrooms = self._count(beds)392 lst.bathrooms = self._count(393 (card.get("bathsRange") or [None])[0])394 out.append(lst)395 return out396 for i, fp in enumerate(plans):397 avail = fp.get("availability") or {}398 adate = "now" if avail.get("now") else (399 avail.get("date") or "")[:10] or None400 if adate and adate != "now" and adate <= today:401 adate = "now"402 lst = self._mk(common, gid, f"-{i}", fp.get("rent"),403 self._unit_type(fp.get("beds")),404 fp.get("size"), today, adate=adate)405 lst.bedrooms = self._count(fp.get("beds"))406 lst.bathrooms = self._count(fp.get("baths"))407 fp_tour = self._tour_url(fp.get("tours"))408 if fp_tour: # la visite du plan précis bat celle de l'immeuble409 lst.details["virtual_tour"] = fp_tour410 if fp.get("furnished") == "yes":411 lst.furnished = True412 out.append(lst)413 return out414415 def fetch(self) -> list[Listing]:416 # le « détail » est une requête GraphQL, pas une page HTML : le417 # fetch_html du cache reçoit le gid et le renvoie tel quel, parse_fn418 # exécute la requête GraphQL.419 # clé v2 : force le re-téléchargement progressif des détails pour420 # capter tours{} (visites virtuelles) et floorPlans.baths ajoutés en421 # vague 2 — les payloads v1 périmés restent utilisés en attendant422 cache = du.TtlDetailCache(self, budget=DETAIL_LIMIT, ttl_days=TTL_DAYS,423 key="v2", fetch_html=lambda gid: gid)424 out: list[Listing] = []425 today = datetime.date.today().isoformat()426 try:427 for slug in CITIES:428 cid = self._city_id(slug)429 if not cid:430 continue431 for card in self._city_listings(cid):432 gid = card.get("id")433 if not gid:434 continue435 node = cache.get(gid, gid,436 lambda g: self._detail(g)) or {}437 out.extend(self._card_listings(card, node, today,438 default_city=slug.title()))439 finally:440 cache.close()441 return out442443 def _mk(self, common: dict, gid: str, suffix: str, price, unit_type,444 size, today, adate=None, price_from=False) -> Listing:445 num = self._numeric_id(gid)446 p = None447 try:448 p = float(price) if price is not None else None449 except (TypeError, ValueError):450 p = None451 details = dict(common.get("details") or {})452 if price_from:453 details["price_from"] = True454 lst = Listing(455 **{k: v for k, v in common.items() if k != "details"},456 external_id=f"{num}{suffix}",457 title=common.get("address") or "Logement à louer",458 unit_type=unit_type,459 price=p,460 price_label=(("À partir de " if price_from else "")461 + (f"{p:,.0f} $/mois".replace(",", " ") if p else "")),462 area_sqft=float(size) if size else None,463 availability_date=adate,464 availability=("Libre immédiatement" if adate == "now"465 else f"Libre le {adate}" if adate else ""),466 details=details,467 )468 return lst469