SPB Git

Repository Public

_livya.py 15.3 KB 364 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/_livya.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-10-2214#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/_livya.py : base COMMUNE des connecteurs de gestionnaires servis91#   par la plateforme Livya (app.livya.com — nouvelle marque de RealVuu).92#   Depuis la refonte Livya du 2026-10-22, les pages projets (/plans, /units)93#   chargent leurs unités côté client via api.realvuu.com (robots.txt interdit94#   tout accès : on ne l'utilise PAS). La page INVENTAIRE du client95#   /fr/{client}/inventory/{selectorId} reste rendue côté serveur (Next.js) :96#   son flux RSC (self.__next_f.push) contient l'inventaire JSON complet du97#   client en UNE page — unités {"unitId": …} (statut, loyer, pièces,98#   chambres/sdb, pi², adresse civique, GPS, attributs) et immeubles99#   {"buildingId": …}. Les selectorId se découvrent dans le même flux RSC de100#   la page d'accueil du client (/fr/{client}, clé "unitSelectorSummaries") ;101#   clé ABSENTE = gabarit changé (erreur franche), clé présente mais VIDE =102#   client sans module inventaire (vrai zéro Livya — cas lsr-gesdev, dont103#   l'inventaire vit surtout chez Planpoint).104#   Sous-classes : définir source_id, client, brand, site_url, default_city105#   et default_inventory (repli selectorId si la découverte casse). Voir106#   atimco.py, phg.py, lsr.py. Clients Livya couverts par des connecteurs107#   dédiés antérieurs : thrace (patron plans d'origine), somex/louis14/108#   quartier_sila (module « plans »).109# -----------------------------------------------------------------------------110from __future__ import annotations111112import json113import re114import time115116from ..schema import Listing117from .base import BaseConnector118119LIVYA = "https://app.livya.com"120121# fragments RSC de Next.js : self.__next_f.push([1,"…"])122_FLIGHT_RE = re.compile(r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')123# immeuble du flux : buildingId, name et slug (ordre des champs stable)124_BUILDING_RE = re.compile(125    r'\{"buildingId":"([0-9a-f-]+)","projectId":"[0-9a-f-]+",'126    r'"phaseId":[^,]*,"name":"([^"]*)","shortName":"[^"]*","slug":"([^"]*)"')127128129def _flight_blob(html: str) -> str:130    """Concatène et décode les fragments RSC d'une page Livya (JSON en clair)."""131    return "".join(json.loads(f'"{c}"') for c in _FLIGHT_RE.findall(html))132133134def _unit_type(rooms) -> str:135    """3.5 -> « 3½ » ; < 1 -> « Studio » (finalize gère 6½+)."""136    try:137        r = float(rooms or 0)138    except (TypeError, ValueError):139        return ""140    if not r:141        return ""142    if r < 1:143        return "Studio"144    return f"{int(r)}½"145146147class LivyaConnector(BaseConnector):148    """Base abstraite (source_id vide = non enregistrée par le registre)."""149150    source_id = ""151    request_delay = 0.8152    max_units = 1500                 # garde-fou global153154    client = ""                      # slug Livya du gestionnaire155    brand = ""                       # préfixe des titres d'annonces156    site_url = ""                    # site public du gestionnaire (référence)157    default_city = ""                # repli si l'unité n'a pas de ville158    default_inventory: list[str] = []  # repli selectorId si la découverte casse159160    # -- découverte des sélecteurs d'inventaire ---------------------------------161    def _inventory_selectors(self) -> list[str]:162        """selectorId des sélecteurs d'unités du client (page /fr/{client}).163164        Clé "unitSelectorSummaries" absente du flux RSC = gabarit Livya165        changé (erreur franche) ; présente mais vide = client sans module166        inventaire (vrai zéro côté Livya).167        """168        blob = _flight_blob(self.get(f"{LIVYA}/fr/{self.client}").text)169        key = '"unitSelectorSummaries":'170        i = blob.find(key)171        if i < 0:172            if self.default_inventory:173                return list(self.default_inventory)174            raise RuntimeError(175                f"unitSelectorSummaries introuvable sur {LIVYA}/fr/"176                f"{self.client} — gabarit Livya changé ?")177        try:178            arr, _ = json.JSONDecoder().raw_decode(blob[i + len(key):])179        except ValueError:180            arr = None181        if not isinstance(arr, list):182            if self.default_inventory:183                return list(self.default_inventory)184            raise RuntimeError(185                "unitSelectorSummaries illisible sur "186                f"{LIVYA}/fr/{self.client} — gabarit Livya changé ?")187        ids = [s.get("selectorId") for s in arr188               if isinstance(s, dict) and s.get("selectorId")]189        return ids or (list(self.default_inventory) if arr else [])190191    # -- extraction du flux RSC --------------------------------------------------192    @staticmethod193    def _units(blob: str) -> list[dict]:194        """Objets unité complets ({"unitId": …}) du flux, dédoublonnés."""195        dec = json.JSONDecoder()196        seen: set[str] = set()197        units: list[dict] = []198        for m in re.finditer(r'\{"unitId"', blob):199            try:200                obj, _ = dec.raw_decode(blob[m.start():m.start() + 60000])201            except Exception:202                continue203            uid = obj.get("unitId")204            if uid and uid not in seen and obj.get("number"):205                seen.add(uid)206                units.append(obj)207        return units208209    def fetch(self) -> list[Listing]:210        selectors = self._inventory_selectors()211        units: dict[str, tuple[dict, str]] = {}      # unitId -> (unité, selectorId)212        buildings: dict[str, tuple[str, str]] = {}   # id -> (nom, slug)213        for sel in selectors:214            url = f"{LIVYA}/fr/{self.client}/inventory/{sel}"215            # 500 Livya transitoires connus (pattern louis14) : retry court216            for attempt in range(3):217                try:218                    blob = _flight_blob(self.get(url).text)219                except Exception:220                    if attempt == 2:221                        raise222                    time.sleep(4 * (attempt + 1))223                    continue224                for u in self._units(blob):225                    units.setdefault(u["unitId"], (u, sel))226                for bid, name, bslug in _BUILDING_RE.findall(blob):227                    buildings.setdefault(bid, (name, bslug))228                break229        if selectors and not units:230            raise RuntimeError(231                f"aucune unité dans le flux RSC des pages inventory de "232                f"{self.client} ({len(selectors)} sélecteur(s)) — format "233                "Livya changé ?")234235        listings: list[Listing] = []236        for u, sel in list(units.values())[: self.max_units]:237            if (u.get("availability") or "").upper() != "AVAILABLE":238                continue239            if not u.get("rental", True):240                continue                 # unités en vente241            if (u.get("segment") or "").upper() != "RESIDENTIAL":242                continue                 # locaux commerciaux exclus243            if (u.get("stateCode") or "QC").upper() != "QC":244                continue                 # garde-fou province (Chartwell & cie)245            listings.append(self._listing(u, sel, buildings))246        return listings247248    # -- une annonce par unité disponible ----------------------------------------249    def _listing(self, u: dict, sel: str,250                 buildings: dict[str, tuple[str, str]]) -> Listing:251        num = str(u.get("number") or "").strip()252        bname, _bslug = buildings.get(u.get("buildingId") or "", ("", ""))253254        url = f"{LIVYA}/fr/{self.client}/inventory/{sel}"255        title = (f"{self.brand} ({bname}) — unité {num}" if bname256                 else f"{self.brand} — unité {num}")257258        address = ", ".join(x for x in (259            (u.get("address") or "").strip(), (u.get("city") or "").strip(),260            (u.get("postalCode") or "").strip()) if x)261262        price = u.get("rentalPrice")263        price = (float(price)264                 if isinstance(price, (int, float)) and price > 1 else None)265        from_price = False266        if price is None:                # prix « à partir de » (préloc/promo)267            base = u.get("startingAtRentalPrice")268            if (u.get("startingAtRental")269                    and isinstance(base, (int, float)) and base > 1):270                price, from_price = float(base), True271272        # disponibilité : date de libération future publiée, sinon « Disponible »273        availability = "Disponible"274        avail_date = None275        fut = u.get("futureAvailability") or {}276        starts = str(fut.get("startsOn") or "")[:10]277        if re.fullmatch(r"20\d{2}-\d{2}-\d{2}", starts):278            avail_date = starts279            availability = f"Disponible à partir du {starts}"280281        # superficie structurée (measurementSystem IMPERIAL -> déjà en pi²)282        area = None283        if (u.get("measurementSystem") or "IMPERIAL").upper() == "IMPERIAL":284            size = u.get("unitSize")285            if isinstance(size, (int, float)) and size > 0:286                area = float(size)287288        amenities = [a["name"] for a in (u.get("attributes") or [])289                     if isinstance(a, dict) and a.get("name")]290291        desc: list[str] = []292        floor_disp = str(u.get("floorDisplayName") or "").strip()293        if floor_disp:294            desc.append(floor_disp)295        if u.get("typeName"):296            desc.append(f"Modèle {u['typeName']}")297        if u.get("roomsBed"):298            desc.append(f"{u['roomsBed']} chambre(s)")299        if u.get("roomsBath"):300            desc.append(f"{u['roomsBath']} salle(s) de bain")301        if u.get("balconySize"):302            desc.append(f"Balcon de {u['balconySize']} pi²")303        precision = str(u.get("pricePrecision") or "").strip()304        if precision:305            desc.append(precision)306        libre = str(u.get("description") or "").strip()307        if libre:308            desc.append(libre)309        if u.get("floorPlanUrl"):310            desc.append(f"Plan : {u['floorPlanUrl']}")311312        details: dict = {"gestionnaire": self.site_url or self.brand}313        if bname:314            details["building"] = bname315        floor_no = str(u.get("floorNumber") or "")316        if floor_no.isdigit():317            details["floor"] = int(floor_no)318319        images = [img.get("fullUrl") for img in (u.get("typeImages") or [])320                  if isinstance(img, dict) and img.get("fullUrl")]321        if u.get("floorPlanImageUrl"):322            images.append(u["floorPlanImageUrl"])323324        try:325            lat = float(u["latitude"]) if u.get("latitude") else None326            lng = float(u["longitude"]) if u.get("longitude") else None327        except (TypeError, ValueError):328            lat = lng = None329330        beds = u.get("roomsBed")331        baths = u.get("roomsBath")332        if baths is not None and u.get("roomsWater"):333            try:334                baths = float(baths) + 0.5 * float(u["roomsWater"])335            except (TypeError, ValueError):336                pass337338        return Listing(339            source=self.source_id,340            external_id=str(u["unitId"]),          # UUID Livya : stable341            url=url,342            title=title,343            address=address,344            sector="",                             # non exposé par le flux345            city=(u.get("city") or "").strip() or self.default_city,346            unit_type=_unit_type(u.get("rooms")),347            bedrooms=(float(beds)348                      if isinstance(beds, (int, float)) and beds else None),349            bathrooms=(float(baths)350                       if isinstance(baths, (int, float)) and baths else None),351            price=price,352            price_label=((f"à partir de {price:.0f} $ /mois" if from_price353                          else f"{price:.0f} $ /mois") if price else ""),354            availability=availability,355            availability_date=avail_date,356            area_sqft=area,357            description=" | ".join(desc),358            amenities=amenities,359            details=details,360            images=images[:12],361            lat=lat,362            lng=lng,363        )364
Files main
Menu

Theme