Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/morguard.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# 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 (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/morguard.py : connecteur Morguard (morguardliving.ca)91# REIT pancanadien (~126 immeubles) sur plateforme Rentsync : le site est une92# SPA mais son backend officiel (website-gateway.rentsync.com, sans auth) est93# interrogé directement — /properties pour les immeubles, /units pour les94# unités disponibles, /photos pour les galeries. Seul le Québec est conservé95# (code postal H/J/G) : 15 immeubles — centre-ville de Montréal (Maisonneuve,96# Crescent, Mackay, des Pins…), Dollard-des-Ormeaux, Côte-Saint-Luc et97# Pointe-Claire. Une annonce par unité disponible (available == 1).98# Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO : quand LOUKA_ONTARIO=1,99# les immeubles ON des marchés cibles (Toronto/GTA, Ottawa, Hamilton, KW)100# sont aussi conservés via leur cityId Rentsync (le gateway n'expose pas de101# nom de ville ni de province — mapping cityId->ville validé par FSA postal ;102# London/Windsor hors marchés cibles exclus). province="ON", adresse « ON ».103# Sans la variable, comportement strictement identique (QC seulement).104# -----------------------------------------------------------------------------105from __future__ import annotations106107import html as htmllib108import os109import re110111from ..schema import Listing112from .base import BaseConnector113114SITE = "https://www.morguardliving.ca"115API = "https://website-gateway.rentsync.com/v1/morguard_invest"116IMG_BASE = "https://s3.amazonaws.com/lws_lift/morguard_invest/images/gallery/1152"117118# Expansion Ontario 2026-08 — gate : sans LOUKA_ONTARIO=1, QC seulement119_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"120121# cityId Rentsync -> ville (le gateway n'expose pas les noms de villes)122_CITIES = {123 1863: "Montréal",124 765: "Dollard-des-Ormeaux",125 33093: "Côte-Saint-Luc",126 2213: "Pointe-Claire",127}128129# cityId Rentsync -> ville Ontario (expansion 2026-08, sous LOUKA_ONTARIO).130# Marchés cibles : Toronto/GTA, Ottawa, Hamilton, Kitchener-Waterloo.131# Mapping validé par FSA des codes postaux du gateway (2026-08-26) ;132# 1607 (London, N6A) et 3370 (Windsor, N8Y) volontairement exclus.133_CITIES_ON = {134 3133: "Toronto", # M6K (Parkdale…)135 2015: "Toronto", # M3A (North York)136 1837: "Mississauga", # L4X137 329: "Brampton", # L6W138 2042: "Oakville", # L6K139 387: "Burlington", # L7T140 1174: "Hamilton", # L8S141 2084: "Ottawa", # K1V…142 1425: "Kitchener", # N2C143 3284: "Waterloo", # N2L144}145146# Nombre de chambres -> type d'unité (convention QC : n½ = n-2 chambres)147_BED_TYPE = {0: "Studio", 1: "3½", 2: "4½", 3: "5½", 4: "6½"}148149_TAG_RE = re.compile(r"<[^>]+>")150_DATE_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})")151152153def _clean(txt: str) -> str:154 txt = htmllib.unescape(htmllib.unescape(txt or ""))155 txt = _TAG_RE.sub(" ", txt)156 return re.sub(r"\s+", " ", txt).strip()157158159class MorguardConnector(BaseConnector):160 source_id = "morguard"161 request_delay = 0.6162 # garde-fou (84 unités QC dispo à l'écriture ; plafond relevé avec l'ON)163 max_units = 900 if _ONTARIO else 300164165 def fetch(self) -> list[Listing]:166 props = (self.get(f"{API}/properties", params={"limit": "300"})167 .json().get("data") or [])168 # Québec : codes postaux H (Mtl), J (couronnes), G (est) ;169 # Ontario (sous LOUKA_ONTARIO) : cityId des marchés cibles.170 buildings: dict[int, dict] = {}171 for p in props:172 postal = (p.get("postal") or "").strip().upper()173 is_qc = postal[:1] in ("H", "J", "G")174 is_on = _ONTARIO and int(p.get("cityId") or 0) in _CITIES_ON175 if not (is_qc or is_on):176 continue177 if (p.get("status") or "") != "enabled":178 continue179 buildings[int(p["id"])] = p180 if not buildings:181 return []182183 ids = "|".join(str(i) for i in sorted(buildings))184 units = (self.get(f"{API}/units", params={185 "where": f"buildingId~in:{ids},status~in:enabled",186 # ON inclus : ~6x plus d'immeubles, plafond relevé en conséquence187 "limit": "1500" if _ONTARIO else "500",188 }).json().get("data") or [])189190 listings: list[Listing] = []191 photo_cache: dict[int, list[str]] = {}192 count = 0193 for u in units:194 try:195 if int(u.get("available") or 0) != 1:196 continue197 b = buildings.get(int(u.get("buildingId") or 0))198 if b is None:199 continue200 if count >= self.max_units:201 break202 count += 1203 listings.append(self._unit_listing(u, b, photo_cache))204 except Exception:205 continue206 return listings207208 # -- galerie photos de l'immeuble (endpoint /photos, mise en cache BD) -----209 def _building_photos(self, bid: int, cache: dict[int, list[str]],210 key: str) -> list[str]:211 if bid in cache:212 return cache[bid]213214 def _fetch() -> dict:215 data = (self.get(f"{API}/photos", params={216 "relations": "buildingsHasPhotos:bhp",217 "where": f"bhp.buildingId~in:{bid}",218 "limit": "40",219 }).json().get("data") or [])220 imgs = [f"{IMG_BASE}/{ph['image']}" for ph in data221 if ph.get("image") and ph.get("active")]222 return {"images": imgs[:25]}223224 payload = self.detail(f"photos-{bid}", key, _fetch)225 cache[bid] = payload.get("images") or []226 return cache[bid]227228 # -- annonce par unité disponible -------------------------------------------229 def _unit_listing(self, u: dict, b: dict,230 photo_cache: dict[int, list[str]]) -> Listing:231 bid = int(b["id"])232 name = _clean(b.get("buildingName") or "")233 street = _clean(f"{b.get('streetNumber') or ''} "234 f"{b.get('streetName') or ''}")235 cid = int(b.get("cityId") or 0)236 if _ONTARIO and cid in _CITIES_ON:237 prov, city = "ON", _CITIES_ON[cid]238 else:239 prov, city = "QC", _CITIES.get(cid, "Montréal")240 postal = (b.get("postal") or "").strip().upper()241 address = f"{street}, {city}, {prov} {postal}".strip(" ,")242 sector = _clean(b.get("neighbourhood") or "")243244 try:245 lat, lng = float(b["latitude"]), float(b["longitude"])246 except (TypeError, KeyError, ValueError):247 lat = lng = None248249 type_name = _clean(u.get("typeName") or "")250 bed = u.get("bed")251 unit_type = _BED_TYPE.get(int(bed), "") if bed is not None else ""252253 rate = u.get("rateMin") or u.get("rate")254 try:255 price = float(rate) if rate else None256 except (TypeError, ValueError):257 price = None258 if price is not None and not (100 <= price <= 20000):259 price = None260261 try:262 bath = float(u.get("bath")) if u.get("bath") is not None else None263 except (TypeError, ValueError):264 bath = None265 try:266 sqft = float(u.get("sqFtMin") or u.get("sqFt") or 0) or None267 except (TypeError, ValueError):268 sqft = None269270 # date de disponibilité ISO (ex. "2026-09-01T00:00:00.000Z")271 avail_date = None272 m = _DATE_RE.match(str(u.get("availabilityDate") or ""))273 if m:274 avail_date = m.group(1)275276 desc = _clean(u.get("description") or "")277 overview = _clean(b.get("buildingOverview") or "")278 description = (f"{desc} {overview}".strip())[:600]279280 furnished = True if int(u.get("furnished") or 0) == 1 else None281 pets = None282 if b.get("petFriendly") is not None:283 pets = "oui" if int(b.get("petFriendly") or 0) == 1 else "non"284285 details: dict = {}286 contact = {}287 if _clean(b.get("phone") or ""):288 contact["phone"] = _clean(b["phone"])289 if _clean(b.get("email") or ""):290 contact["email"] = _clean(b["email"])291 if contact:292 details["contact"] = contact293 parking = _clean(b.get("parking") or "")294 if parking:295 details["parking"] = {"available": True, "notes": parking[:120]}296297 # galerie : revisitée seulement quand l'immeuble est modifié298 images = self._building_photos(299 bid, photo_cache, key=str(b.get("modified") or ""))300301 perma = (b.get("permaLink") or "").strip("/")302 url = f"{SITE}/residential/{perma}" if perma else SITE303304 return Listing(305 source=self.source_id,306 external_id=str(u["id"]),307 url=url,308 title=f"{name} — {type_name}" if type_name else name,309 address=address,310 sector=sector,311 city=city,312 province=prov,313 unit_type=unit_type,314 bedrooms=float(bed) if bed is not None else None,315 bathrooms=bath,316 price=price,317 price_label=f"À partir de {int(price)} $/mois" if price else "",318 availability_date=avail_date,319 area_sqft=sqft,320 pets=pets,321 furnished=furnished,322 description=description,323 details=details,324 images=images,325 lat=lat,326 lng=lng,327 )328