SPB Git

Repository Public

rentsyncgw.py 22.6 KB 519 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/rentsyncgw.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/rentsyncgw.py : connecteur GÉNÉRIQUE passerelle Rentsync91#   « nouvelle génération » (website-gateway.rentsync.com)92#   Plusieurs gros gestionnaires ontariens ont migré leur site vers la SPA93#   Rentsync nouvelle génération (bundles cdn.rentsync.com/site/<siteKey>) qui94#   parle à la passerelle JSON PUBLIQUE — aucune auth, aucun anti-bot :95#     https://website-gateway.rentsync.com/v1/<siteKey>/96#       properties?limit=500      → immeubles (adresse, GPS, cityId, permaLink,97#           buildingTypeId, animaux, description, modified) ; paginé meta.totalPages98#       cities?where=id~in:X|Y&relations=province:p → nom de ville + province99#           (filtre ON strict ; séparateur multi-valeurs « | »)100#       units?where=status:enabled,available~in:1&limit=750&page=N101#           → types d'unités AVEC vacance (bed/bath/pi²/loyer/date), paginés102#       photos?relations=buildingsHasPhotos:bhp&where=bhp.buildingId~in:…103#           → galeries par lots d'immeubles (images S3 lws_lift, taille « full »)104#   Images : https://s3.amazonaws.com/lws_lift/<img_key>/images/gallery/full/…105#   — la clé S3 peut différer du siteKey (drewlo_rebuild → drewlo,106#   panoramic_properties → panoramic ; validé en live HEAD 200 vs 403), d'où107#   la clé `img_key` du registre.108#   Plutôt que N modules copiés-collés (homestead.py et skyline.py sont les109#   connecteurs canoniques de cette passerelle), ce module lit le registre110#   data/rentsyncgw_clients.json ({id, name, site, site_key, img_key…},111#   validés en live le 2026-08-27) et GÉNÈRE une sous-classe par client112#   (source_id = "rsgw_<id>", ex. "rsgw_drewlo"), déposée dans les globals du113#   module pour le registre auto-découvrant (connectors/__init__.py).114#   Extraction modelée sur skyline.py : UNE annonce par type d'unité disponible,115#   regroupée par (immeuble, typeName, cc, sdb) — certains flux publient une116#   rangée PAR APPARTEMENT du même plan (champ `number`) : loyer plancher117#   « à partir de », date la plus proche, identifiant stable immeuble+plan.118#   Filtre province ON strict via /cities, filtre types non résidentiels119#   (office/retail/industrial/construction/subdivision — Sterling Karamar et120#   Drewlo mélangent commercial et chantiers dans le même flux). Tout vient de121#   l'API par lots : aucune page détail à visiter, pas de self.detail().122#   Clients au 2026-08-27 : Sterling Karamar (~15 000 unités, 217 propriétés),123#   Drewlo Holdings (~10 000, 108), Panoramic Properties (Sudbury, 49).124#   Expansion Ontario — activer via LOUKA_ONTARIO=1 : sans la variable, toutes125#   les classes générées sont `disabled` (exclues du registre), prod QC intacte.126# -----------------------------------------------------------------------------127from __future__ import annotations128129import html as htmllib130import json131import os132import re133from pathlib import Path134135from bs4 import BeautifulSoup136137from ..schema import Listing, normalize_unit_type, strip_accents138from .base import BaseConnector139140# Gate expansion Ontario : rien ne s'active en prod sans LOUKA_ONTARIO=1141_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"142143REGISTRY_PATH = Path(__file__).resolve().parents[2] / "data" / \144    "rentsyncgw_clients.json"145GATEWAY = "https://website-gateway.rentsync.com/v1"146IMG_BASE = "https://s3.amazonaws.com/lws_lift"147148# Types d'immeubles NON résidentiels du flux (buildingTypeId) — Sterling149# Karamar publie 46 locaux commerciaux, Drewlo des chantiers (« coming-soon »)150# et des subdivisions de maisons neuves À VENDRE : hors sujet pour Lou-Ka.151_NON_RESIDENTIAL = {152    "office", "retail", "warehouse", "industrial", "commercial", "land",153    "construction", "subdivision", "motel", "hotel", "parking", "storage",154}155156# secteur : le champ `neighbourhood` contient parfois le comté (« Grey157# County », « Niagara Region ») — pas un quartier, on l'écarte (cf. skyline)158_COUNTY_RE = re.compile(r"\b(county|region|district|municipality)\b", re.I)159_ISO_DATE_RE = re.compile(r"^20\d{2}-\d{2}-\d{2}")160161162def _load_registry() -> list[dict]:163    """Entrées validées du registre (site_key présent, status = valide)."""164    try:165        data = json.loads(REGISTRY_PATH.read_text("utf-8"))166    except (OSError, ValueError):167        return []168    return [c for c in data.get("clients") or []169            if c.get("site_key") and c.get("status") == "valide"]170171172class RentsyncGatewayConnector(BaseConnector):173    """Base commune des connecteurs passerelle Rentsync générés — non174    enregistrée elle-même (source_id vide) ; chaque sous-classe reçoit son175    entrée de registre dans l'attribut de classe `client`."""176177    source_id = ""            # les sous-classes générées le définissent178    client: dict = {}         # entrée du registre (name, site, site_key…)179    request_delay = 0.8       # politesse — même rythme que skyline/homestead180    max_properties = 300      # garde-fou immeubles (plus gros : 217 au 2026-08)181    max_listings = 1500       # garde-fou global d'annonces182    max_images = 15183    page_limit = 750          # taille de page maximale de la passerelle184    photo_chunk = 40          # immeubles par requête /photos185186    # -- accès passerelle -------------------------------------------------------187    def _get_json(self, path: str, params: dict) -> dict:188        site = (self.client.get("site") or "").rstrip("/")189        resp = self.get(f"{GATEWAY}/{self.client['site_key']}{path}",190                        params=params, headers={191                            "Accept": "application/json",192                            "Origin": site,193                            "Referer": site + "/",194                            "rs-lang": "en",195                        })196        return resp.json()197198    def _paged(self, path: str, params: dict, max_pages: int = 20) -> list[dict]:199        """Concatène toutes les pages d'un endpoint (meta.totalPages)."""200        out: list[dict] = []201        page = 1202        while page <= max_pages:203            data = self._get_json(path, {**params, "page": page})204            out.extend(data.get("data") or [])205            meta = data.get("meta") or {}206            if page >= int(meta.get("totalPages") or 1):207                break208            page += 1209        return out210211    # -- villes : cityId -> (nom, code province) --------------------------------212    def _cities(self, city_ids: set[int]) -> dict[int, tuple[str, str]]:213        if not city_ids:214            return {}215        ids = "|".join(str(i) for i in sorted(city_ids))216        rows = self._paged("/cities", {217            "where": f"id~in:{ids}",218            "relations": "province:p",219            "limit": self.page_limit,220        })221        out: dict[int, tuple[str, str]] = {}222        for c in rows:223            prov = c.get("province") or {}224            out[int(c["id"])] = ((c.get("cityName") or "").strip(),225                                 (prov.get("provinceCode") or "").strip().upper())226        return out227228    # -- galeries photo par lots d'immeubles ------------------------------------229    def _photos(self, building_ids: list[int]) -> dict[int, list[str]]:230        img_base = f"{IMG_BASE}/{self.client.get('img_key') or self.client['site_key']}" \231                   "/images/gallery/full"232        out: dict[int, list[str]] = {}233        for i in range(0, len(building_ids), self.photo_chunk):234            chunk = building_ids[i:i + self.photo_chunk]235            ids = "|".join(str(b) for b in chunk)236            try:237                rows = self._paged("/photos", {238                    "relations": "buildingsHasPhotos:bhp",239                    "where": f"bhp.buildingId~in:{ids}",240                    "orderBy": "bhp.orderBy~asc",241                    "limit": self.page_limit,242                })243            except Exception:244                continue    # galerie manquante : annonces sans photo plutôt que rien245            for ph in rows:246                bid = ph.get("buildingId")247                img = (ph.get("image") or "").strip()248                if not bid or not img:249                    continue250                urls = out.setdefault(int(bid), [])251                if len(urls) < self.max_images:252                    u = f"{img_base}/{img}"253                    if u not in urls:254                        urls.append(u)255        return out256257    # -- collecte ---------------------------------------------------------------258    def fetch(self) -> list[Listing]:259        props = self._paged("/properties",260                            {"limit": 500})[: self.max_properties]261262        # écarter commerces/chantiers/subdivisions du flux (buildingTypeId)263        props = [p for p in props264                 if str(p.get("buildingTypeId") or "").strip().lower()265                 not in _NON_RESIDENTIAL]266267        # immeubles gérés pour un tiers déjà couvert par un connecteur dédié268        # (ex. Greenrock via sterlingkaramar) — exclus par importId269        excl = {s.strip() for s in (self.client.get("exclude_import_ids") or [])}270        if excl:271            props = [p for p in props272                     if (p.get("importId") or "").strip() not in excl]273274        # villes -> filtre Ontario strict (certains flux débordent de l'ON)275        cities = self._cities({int(p["cityId"]) for p in props276                               if p.get("cityId")})277        on_props: dict[int, dict] = {}278        for p in props:279            name, prov = cities.get(int(p.get("cityId") or 0), ("", ""))280            if prov != "ON" or not name:281                continue282            p["_city"] = name283            on_props[int(p["id"])] = p284285        # types d'unités avec vacance : certains flux publient une rangée PAR286        # APPARTEMENT (champ `number`) du même plan — regrouper par287        # (immeuble, plan, cc, sdb) pour une annonce par type d'unité288        units = self._paged("/units", {289            "where": "status:enabled,available~in:1",290            "limit": self.page_limit,291        })292        by_building: dict[int, dict[tuple, list[dict]]] = {}293        for u in units:294            if u.get("hideSuiteTypeWebsite"):295                continue296            bid = int(u.get("buildingId") or 0)297            if bid not in on_props:298                continue299            key = ((u.get("typeName") or "").strip().lower(),300                   u.get("bedMin", u.get("bed")),301                   u.get("bathMin", u.get("bath")))302            by_building.setdefault(bid, {}).setdefault(key, []).append(u)303304        # galeries des seuls immeubles qui produisent des annonces305        photos = self._photos(sorted(by_building))306307        listings: list[Listing] = []308        for bid, groups in by_building.items():309            if len(listings) >= self.max_listings:310                break311            p = on_props[bid]312            try:313                base = self._building_ctx(p, photos.get(bid) or [])314            except Exception:315                continue316            for rows in groups.values():317                if len(listings) >= self.max_listings:318                    break319                try:320                    listings.append(self._listing(bid, rows, base))321                except Exception:322                    continue323        return listings324325    # -- contexte immeuble (partagé entre ses annonces) --------------------------326    def _building_ctx(self, p: dict, images: list[str]) -> dict:327        city = p["_city"]328        street = " ".join(x for x in (329            (p.get("streetNumber") or "").strip(),330            (p.get("streetName") or "").strip()) if x)331        postal = (p.get("postal") or "").strip()332        address = ", ".join(x for x in (street, city) if x)333        if address:334            address += f", ON {postal}".rstrip()335336        # secteur : quartier seulement (écarter comtés/« regions » du flux)337        sector = (p.get("neighbourhood") or "").strip()338        if _COUNTY_RE.search(sector):339            sector = ""340341        try:342            lat = float(p["latitude"]) if p.get("latitude") else None343            lng = float(p["longitude"]) if p.get("longitude") else None344        except (TypeError, ValueError):345            lat = lng = None346347        # caractéristiques de l'immeuble : HTML doublement échappé dans le flux348        amenities: list[str] = []349        feats = htmllib.unescape(p.get("buildingFeatures") or "")350        for li in BeautifulSoup(feats, "html.parser").find_all("li"):351            t = li.get_text(" ", strip=True)352            if t and t not in amenities:353                amenities.append(t)354355        # description : aperçu de l'immeuble (+ détails des suites si présents)356        desc_html = (p.get("buildingOverview") or "") + " " + \357                    (p.get("suiteDetails") or "")358        desc = BeautifulSoup(htmllib.unescape(desc_html),359                             "html.parser").get_text(" ", strip=True)360361        # animaux : drapeaux structurés du flux362        pets = None363        if p.get("petsNotAllowed") == 1:364            pets = "non"365        elif p.get("petFriendly") == 1:366            pets = "oui"367368        details: dict = {}369        contact: dict = {}370        if (p.get("phone") or "").strip():371            contact["phone"] = p["phone"].strip()372        email = (p.get("email") or "").split(",")[0].strip()373        # adresses de tracking (leadmanaging…) : pas un vrai contact public374        if email and "leadmanaging" not in email.lower():375            contact["email"] = email376        if contact:377            details["contact"] = contact378        try:379            if int(p.get("yearBuilt") or 0) > 1800:380                details["Année de construction"] = int(p["yearBuilt"])381            if int(p.get("floorCount") or 0) > 0:382                details["Étages"] = int(p["floorCount"])383        except (TypeError, ValueError):384            pass385386        # fiche : site du client + fullPermaLink (validé 200 sur les 3 clients)387        site = (self.client.get("site") or "").rstrip("/")388        perma = (p.get("fullPermaLink") or "").strip().strip("/")389        url = f"{site}/{perma}" if perma else \390            (self.client.get("listing_url") or site)391392        return {"city": city, "address": address, "sector": sector,393                "lat": lat, "lng": lng, "amenities": amenities, "desc": desc,394                "pets": pets, "details": details, "url": url,395                "images": images[: self.max_images],396                # nom : entités HTML dans certains flux (« &amp; » chez Sterling)397                "name": htmllib.unescape(p.get("buildingName") or "").strip()}398399    # -- une annonce par type d'unité disponible (rangées regroupées) ------------400    def _listing(self, bid: int, rows: list[dict], b: dict) -> Listing:401        u = rows[0]402        type_name = (u.get("typeName") or "").strip()403        unit_type = normalize_unit_type(type_name)404        bed = u.get("bedMin", u.get("bed"))405        bath = u.get("bathMin", u.get("bath"))406        if bed is not None and (not unit_type or unit_type == type_name):407            # plans nommés (« Elgin », « Tempo »…) : dériver des chambres408            unit_type = ("Studio" if int(bed) == 0409                         else normalize_unit_type(f"{int(bed)} chambres"))410411        # loyer : plancher du groupe (masqué sur le site si hideRateWebsites=1)412        rates: list[float] = []413        for r in rows:414            if r.get("hideRateWebsites"):415                continue416            try:417                lo = float(r.get("rateMin") or r.get("rate") or 0)418                hi = float(r.get("rateMax") or lo)419            except (TypeError, ValueError):420                continue421            if lo > 0:422                rates += [lo, max(hi, lo)]423        price = min(rates) if rates else None424        price_label = ""425        if price is not None:426            price_label = (f"À partir de {price:.0f} $" if max(rates) > price427                           else f"{price:.0f} $ /mois")428429        # superficie plausible seulement (le flux publie parfois 0)430        area = None431        for r in rows:432            try:433                v = float(r.get("sqFtMin") or r.get("sqFt") or 0)434            except (TypeError, ValueError):435                continue436            if 80 <= v <= 20000 and (area is None or v < area):437                area = v438439        # disponibilité : date structurée la plus proche du groupe440        dates = sorted(str(r.get("availabilityDate") or "").strip()[:10]441                       for r in rows442                       if _ISO_DATE_RE.match(str(r.get("availabilityDate")443                                                  or "")))444        avail_date = dates[0] if dates else None445        availability = f"Disponible le {avail_date}" if avail_date \446            else "Disponible"447        if len(rows) > 1:448            availability += f" — {len(rows)} unités"449450        details = dict(b["details"])451        if (u.get("leaseTerm") or "").strip():452            details["Bail"] = u["leaseTerm"].strip()453454        # identifiant stable : immeuble + plan (les ids d'appartements roulent)455        slug = re.sub(r"[^a-z0-9]+", "-",456                      strip_accents(type_name.lower())).strip("-")457        ext = f"{bid}-{slug or 'u'}"458        if bed is not None or bath is not None:459            ext += f"-{bed}-{bath}"460461        return Listing(462            source=self.source_id,463            external_id=ext,464            url=b["url"],465            title=f"{b['name']} — {type_name}" if type_name else b["name"],466            address=b["address"],467            sector=b["sector"],468            city=b["city"],469            province="ON",470            unit_type=unit_type,471            bedrooms=float(bed) if bed is not None else None,472            bathrooms=float(bath) if bath else None,473            price=price,474            price_label=price_label,475            availability=availability,476            availability_date=avail_date,477            area_sqft=area,478            pets=b["pets"],479            furnished=True if rows and all(r.get("furnished") == 1480                                           for r in rows) else None,481            description=b["desc"][:600],482            amenities=b["amenities"][:25],483            details=details,484            images=b["images"],485            lat=b["lat"],486            lng=b["lng"],487        )488489490# -----------------------------------------------------------------------------491# Génération : une sous-classe par client du registre, déposée dans les globals492# du module — connectors/__init__.py (scan de vars(module)) les découvre alors493# comme n'importe quel connecteur écrit à la main.494# -----------------------------------------------------------------------------495def _make_connector(entry: dict) -> type[RentsyncGatewayConnector]:496    cls = type(497        f"Rsgw{re.sub(r'[^A-Za-z0-9]', '', entry['id']).capitalize()}Connector",498        (RentsyncGatewayConnector,),499        {500            "source_id": f"rsgw_{entry['id']}",501            "client": entry,502            # Expansion Ontario — activer via LOUKA_ONTARIO=1503            # (voir gestion-immobiliere-ontario.md)504            "disabled": not _ONTARIO,505            "__doc__": f"Connecteur passerelle Rentsync généré — "506                       f"{entry.get('name')} (siteKey {entry.get('site_key')}).",507        },508    )509    return cls510511512def _register_all() -> None:513    for entry in _load_registry():514        cls = _make_connector(entry)515        globals()[cls.__name__] = cls516517518_register_all()519
Files main
Menu

Theme