SPB Git

Repository Public

buildium.py 20.5 KB 490 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/buildium.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/buildium.py : connecteur GÉNÉRIQUE Buildium (managebuilding.com)91#   La longue traîne des petits gestionnaires ontariens (Sarnia, Chatham-Kent,92#   Cobourg, Kingston, Ottawa, le Nord…) publie ses annonces sur le portail93#   Buildium : `https://<sous-domaine>.managebuilding.com/Resident/public/rentals`.94#   Contrairement à ce qu'on pouvait craindre, PAS besoin de rendu JS : Buildium95#   sert deux mises en page, toutes deux exploitables en HTML brut :96#     - « moderne » : cartes `a.featured-listing` rendues serveur, avec97#       data-bedrooms/-bathrooms/-rent/-square-feet/-location/-type ;98#     - « héritée » : redirection 302 vers PublicPages/ApartmentSearch.aspx dont99#       le viewmodel DotVVM (`__dot_viewmodel_root`) embarque les annonces en100#       JSON complet (city/state/postalcode, description, contact…).101#   Plutôt que N modules copiés-collés, ce module lit le registre102#   data/buildium_clients.json ({id, name, subdomain…}, sous-domaines découverts103#   via Serper/sites vitrines et validés en live le 2026-08-27) et GÉNÈRE une104#   sous-classe de BaseConnector par client (source_id = "bld_<id>"), déposée105#   dans les globals du module pour le registre auto-découvrant106#   (connectors/__init__.py). Même gabarit que liftsystem.py.107#   Les portails sont pancanadiens/US : filtre province strict (ON/QC) sur le108#   data-location (moderne) ou le champ state (héritée), et filtre résidentiel109#   longue durée (exclusion parking, entreposage, commercial, court terme).110#   Galerie photo de la fiche via le cache BD self.detail() (revisitée quand la111#   ligne de la liste change) ; miniatures `_LxH` remises en pleine résolution.112#113#   Expansion Ontario — activer via LOUKA_ONTARIO=1114#   (voir gestion-immobiliere-ontario.md) : sans la variable, toutes les115#   classes générées sont `disabled` et donc exclues du registre / de la prod.116# -----------------------------------------------------------------------------117from __future__ import annotations118119import hashlib120import html as htmllib121import json122import os123import re124from datetime import datetime125from pathlib import Path126from urllib.parse import urljoin127128from bs4 import BeautifulSoup129130from ..schema import Listing, normalize_unit_type131from .base import BaseConnector132133# Gate expansion Ontario : rien ne s'active en prod sans LOUKA_ONTARIO=1134_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"135136REGISTRY_PATH = Path(__file__).resolve().parents[2] / "data" / \137    "buildium_clients.json"138139# Provinces couvertes par Lou-Ka — les portails Buildium servent tout le140# Canada et les États-Unis (codes d'état à 2 lettres aussi) : tout le reste141# est ignoré au fetch.142_PROVINCES = {"ON", "QC"}143144# Types de propriété NON résidentiels de la mise en page moderne (data-type) —145# stationnements, entreposage et commercial sont hors sujet pour Lou-Ka.146_NON_RESIDENTIAL_TYPES = {147    "parkingspace", "parking", "storage", "commercial", "commercialother",148    "office", "retail", "industrial", "warehouse", "shoppingcenter", "land",149}150151# Filet complémentaire sur le titre/type d'unité (la mise en page héritée n'a152# pas de data-type fiable ; certains clients titrent « PARKING - … »).153_NON_RESIDENTIAL_RE = re.compile(154    r"\b(parking|stationnement|storage|entreposage|locker|garage only|"155    r"commercial|office space|retail|warehouse)\b", re.I)156157# Locations court terme / vacances (hors sujet : Lou-Ka = logements au mois)158_SHORT_TERM_RE = re.compile(159    r"\b(short[\s-]?term|nightly|per night|par nuit|vacation rental|"160    r"weekly rate|airbnb|court terme|campsites?|campground|nature camp)\b",161    re.I)162163# miniatures Buildium : « <hash>_406x539.jpeg » -> pleine résolution sans suffixe164_THUMB_SUFFIX_RE = re.compile(r"_\d{2,4}x\d{2,4}(\.[a-z]{3,4})$", re.I)165166# date de disponibilité de la mise en page héritée (« Friday, August 15, 2025 »)167_LEGACY_DATE_FMT = "%A, %B %d, %Y"168169170def _load_registry() -> list[dict]:171    """Entrées validées du registre (subdomain présent, status == valide)."""172    try:173        data = json.loads(REGISTRY_PATH.read_text("utf-8"))174    except (OSError, ValueError):175        return []176    return [c for c in data.get("clients") or []177            if c.get("subdomain") and c.get("status") == "valide"]178179180def _full_image(url: str) -> str:181    """Remet une miniature Buildium (…_406x539.jpeg) en pleine résolution."""182    return _THUMB_SUFFIX_RE.sub(r"\1", url.replace("&amp;", "&")183                                .replace("&isPreview=true", ""))184185186class BuildiumConnector(BaseConnector):187    """Base commune des connecteurs Buildium générés — non enregistrée188    elle-même (source_id vide) ; chaque sous-classe reçoit son entrée de189    registre dans l'attribut de classe `client`."""190191    source_id = ""            # les sous-classes générées le définissent192    client: dict = {}         # entrée du registre (name, subdomain, site…)193    request_delay = 1.0       # politesse — petits gestionnaires, on y va mollo194    max_listings = 300        # garde-fou (plus gros client : Sleepwell, 130)195    max_images = 20196197    @property198    def base_url(self) -> str:199        return f"https://{self.client['subdomain']}.managebuilding.com"200201    def fetch(self) -> list[Listing]:202        resp = self.get(self.base_url + "/Resident/public/rentals")203        page = resp.text204        soup = BeautifulSoup(page, "html.parser")205206        cards = soup.select("a.featured-listing")207        if cards:                                   # mise en page moderne208            rows = [self._listing_modern(c) for c in cards]209        elif "__dot_viewmodel_root" in page:        # mise en page héritée210            rows = [self._listing_legacy(d) for d in self._legacy_rows(page)]211        else:       # portail sans annonces publiques (login…) : rien à faire212            return []213214        listings: list[Listing] = []215        for lst in rows:216            if lst is None:217                continue218            if len(listings) >= self.max_listings:  # garde-fou APRÈS filtres219                break220            listings.append(lst)221        return listings222223    # -- mise en page moderne : une annonce par carte a.featured-listing -------224    def _listing_modern(self, card) -> Listing | None:225        try:226            href = card.get("href") or ""227            m = re.search(r"/Resident/public/rentals/(\d+)", href)228            if not m:229                return None230            pid = m.group(1)231232            # data-location = « Windsor,ON|N9B 2N6 » — filtre province strict233            loc = card.get("data-location") or ""234            city, _, rest = loc.partition(",")235            prov, _, postal = rest.partition("|")236            prov = prov.strip().upper()237            if prov not in _PROVINCES:238                return None239            city, postal = city.strip(), postal.strip()240241            ptype = (card.get("data-type") or "").strip().lower()242            if ptype in _NON_RESIDENTIAL_TYPES:243                return None                 # stationnement/commerce : hors sujet244245            def txt(sel: str) -> str:246                el = card.select_one(sel)247                return el.get_text(" ", strip=True) if el else ""248249            title = txt(".featured-listing__title")250            desc_excerpt = txt(".featured-listing__description")251            if _NON_RESIDENTIAL_RE.search(f"{title} {desc_excerpt}") or \252                    _SHORT_TERM_RE.search(f"{title} {desc_excerpt}"):253                return None254255            # chambres / salles de bain / loyer / pi² : attributs structurés —256            # jamais de valeur inventée (0 pi² = non renseigné chez Buildium)257            def num(attr: str) -> float | None:258                try:259                    return float(card.get(attr))260                except (TypeError, ValueError):261                    return None262            bedrooms = num("data-bedrooms")263            bathrooms = num("data-bathrooms")264            price = num("data-rent")265            if price is not None and price <= 0:266                price = None267            area = num("data-square-feet")268            if area is not None and not 80 <= area <= 20000:269                area = None270271            unit_type = ""272            if bedrooms is not None:273                unit_type = "Studio" if bedrooms == 0 else \274                    normalize_unit_type(f"{bedrooms:g} chambres")275276            availability = txt(".featured-listing__availability")277278            # adresse civique : le titre Buildium EST la rue (+ n° d'unité)279            address = ", ".join(x for x in (title, city) if x)280            if address and prov:281                address += f", {prov} {postal}".rstrip()282283            url = urljoin(self.base_url, href)284285            # aperçu photo de la carte (miniature -> pleine résolution)286            preview = ""287            img = card.select_one("img.featured-listing__image")288            if img and img.get("src"):289                preview = _full_image(urljoin(self.base_url, img["src"]))290291            # fiche détail (description complète + galerie) via le cache BD :292            # revisitée seulement quand la carte de la liste change293            feed_key = hashlib.sha1("|".join(str(x) for x in (294                card.get("data-rent"), availability, preview,295                card.get("data-bedrooms"), desc_excerpt[:80],296            )).encode("utf-8")).hexdigest()297            d = self.detail(pid, feed_key, lambda: self._fetch_detail(url))298            description = (d.get("description") or desc_excerpt).strip()299            images = [u for u in [preview] + list(d.get("images") or []) if u]300            images = list(dict.fromkeys(images))    # dédup en gardant l'ordre301302            return Listing(303                source=self.source_id,304                external_id=pid,305                url=url,306                title=title,307                address=address,308                city=city,309                province=prov,310                unit_type=unit_type,311                bedrooms=bedrooms,312                bathrooms=bathrooms,313                price=price,314                price_label=f"{price:.0f} $ /mois" if price else "",315                availability=availability,316                area_sqft=area,317                description=description[:1200],318                images=images[: self.max_images],319            )320        except Exception:321            return None322323    def _fetch_detail(self, url: str) -> dict:324        """Description complète + galerie de la fiche (mise en page moderne)."""325        out: dict = {"images": [], "description": ""}326        if not url:327            return out328        try:329            soup = BeautifulSoup(self.get(url).text, "html.parser")330        except Exception:331            return out332        desc = soup.select_one(".unit-detail__description")333        if desc:334            out["description"] = desc.get_text("\n", strip=True)335        gallery = soup.select_one(".unit-detail__gallery")336        if gallery:337            images: list[str] = []338            for el in gallery.find_all(("img", "a")):339                u = el.get("src") or el.get("href") or ""340                if "files/download" not in u:341                    continue342                u = _full_image(urljoin(self.base_url, u))343                if u not in images:344                    images.append(u)345            out["images"] = images[: self.max_images]346        return out347348    # -- mise en page héritée : annonces embarquées dans le viewmodel DotVVM ---349    def _legacy_rows(self, page: str) -> list[dict]:350        """Extrait ContentViewModel.Listings du JSON __dot_viewmodel_root."""351        marker = "__dot_viewmodel_root value='"352        i = page.find(marker)353        if i < 0:354            return []355        start = i + len(marker)356        end = page.find("'", start)     # le JSON encode ses ' en &#39;357        try:358            vm = json.loads(htmllib.unescape(page[start:end]))359        except ValueError:360            return []361        rows = (((vm.get("viewModel") or {}).get("ContentViewModel") or {})362                .get("Listings") or [])363        # chaque ligne est une liste de paires {Key, Value}364        return [{kv.get("Key"): kv.get("Value") for kv in row365                 if isinstance(kv, dict)}366                for row in rows if isinstance(row, list)]367368    def _listing_legacy(self, d: dict) -> Listing | None:369        try:370            pid = str(d.get("listingid") or "").strip()371            prov = str(d.get("state") or "").strip().upper()372            if not pid or prov not in _PROVINCES:373                return None374375            title = (d.get("buildingname") or d.get("propertyname") or "").strip()376            unittype_src = (d.get("unittype") or "").strip()   # « 3 Bed - 1 Bath »377            description = (d.get("unitdescription")378                           or d.get("propertydescription") or "").strip()379            if _NON_RESIDENTIAL_RE.search(f"{title} {unittype_src}") or \380                    _SHORT_TERM_RE.search(f"{title} {unittype_src} "381                                          f"{description[:400]}"):382                return None383384            city = (d.get("city") or "").strip()385            postal = (d.get("postalcode") or "").strip()386            street = (d.get("line1") or "").strip() or title387            address = ", ".join(x for x in (street, city) if x)388            if address:389                address += f", {prov} {postal}".rstrip()390391            # chambres/bains : « 3 Bed » / « 1.5 Bath » — sinon None (inconnu)392            def count(text: str) -> float | None:393                m = re.match(r"\s*(\d+(?:\.\d+)?)", str(text or ""))394                return float(m.group(1)) if m else None395            bedrooms = count(d.get("bedtypedesc"))396            bathrooms = count(d.get("bathtypedesc"))397            unit_type = ""398            if bedrooms is not None:399                unit_type = "Studio" if bedrooms == 0 else \400                    normalize_unit_type(f"{bedrooms:g} chambres")401402            try:403                price = float(d.get("listingrent") or 0) or None404            except (TypeError, ValueError):405                price = None406            try:407                area = float(d.get("squarefootage") or 0)408                area = area if 80 <= area <= 20000 else None409            except (TypeError, ValueError):410                area = None411412            # disponibilité : format anglais long et fixe du viewmodel413            availability = str(d.get("availabilitydate") or "").strip()414            avail_date = None415            try:416                avail_date = datetime.strptime(417                    availability, _LEGACY_DATE_FMT).date().isoformat()418            except ValueError:419                pass420421            details: dict = {}422            contact = {k: str(d.get(f"contact{k}") or "").strip()423                       for k in ("phone", "email")}424            contact = {k: v for k, v in contact.items() if v}425            if contact:426                details["contact"] = contact427428            url = (f"{self.base_url}/Resident/PublicPages/apartmentdetail.aspx"429                   f"?listingId={pid}&unitid={d.get('unitid') or ''}"430                   f"&buildingid={d.get('buildingid') or ''}")431432            images = []433            img = str(d.get("imageUrl") or "").strip()434            if img and "files/download" in img:435                images.append(_full_image(urljoin(self.base_url, img)))436437            return Listing(438                source=self.source_id,439                external_id=pid,440                url=url,441                title=title,442                address=address,443                city=city,444                province=prov,445                unit_type=unit_type,446                bedrooms=bedrooms,447                bathrooms=bathrooms,448                price=price,449                price_label=f"{price:.0f} $ /mois" if price else "",450                availability=availability,451                availability_date=avail_date,452                area_sqft=area,453                description=description[:1200],454                details=details,455                images=images[: self.max_images],456            )457        except Exception:458            return None459460461# -----------------------------------------------------------------------------462# Génération : une sous-classe par client du registre, déposée dans les globals463# du module — connectors/__init__.py (scan de vars(module)) les découvre alors464# comme n'importe quel connecteur écrit à la main.465# -----------------------------------------------------------------------------466def _make_connector(entry: dict) -> type[BuildiumConnector]:467    cls = type(468        f"Bld{re.sub(r'[^A-Za-z0-9]', '', entry['id']).capitalize()}Connector",469        (BuildiumConnector,),470        {471            "source_id": f"bld_{entry['id']}",472            "client": entry,473            # Expansion Ontario — activer via LOUKA_ONTARIO=1474            # (voir gestion-immobiliere-ontario.md)475            "disabled": not _ONTARIO,476            "__doc__": f"Connecteur Buildium généré — {entry.get('name')} "477                       f"({entry.get('subdomain')}.managebuilding.com).",478        },479    )480    return cls481482483def _register_all() -> None:484    for entry in _load_registry():485        cls = _make_connector(entry)486        globals()[cls.__name__] = cls487488489_register_all()490
Files main
Menu

Theme