Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/solaris.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-10-2514#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/solaris.py : connecteur Solaris Boisbriand (solarisboisbriand.com)91# Condos locatifs neufs au 1030, rue des Francs-Bourgeois, Boisbriand92# (Faubourg Boisbriand). Refonte 2026-10 : l'ancien site Wix (/plans,93# 3 cartes par TYPOLOGIE) a été remplacé par un site custom rendu serveur.94# La page /appartements/ expose maintenant les UNITÉS réellement libres95# (section data-live="units", <li data-unit="702">…) avec n°, typologie,96# chambres, pi², prix exact et date de libération — granularité : UNITÉ.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import html as _html101import os102import re103import time104from urllib.parse import quote105106import requests107108from ..schema import Listing109from .base import BaseConnector110111BASE = "https://solarisboisbriand.com"112PLANS_URL = f"{BASE}/appartements/"113114ADDRESS = "1030, rue des Francs-Bourgeois, Boisbriand"115CITY = "Boisbriand"116117SECTION_RE = re.compile(r'data-live="units".*?</ul>', re.S)118COUNT_RE = re.compile(r'data-count="(\d+)"')119UNIT_LI_RE = re.compile(r'<li[^>]*\bdata-unit="(\d+)"(.*?)</li>', re.S)120# « 4½ · 2 chambres 875 pi² 2 140 $ /mois Libre maintenant Photos et plan121# Visiter » (texte plat). 2026-10-24 : le bouton « Plan » est devenu122# « Photos et plan » (+ lien « Visiter ») — l'alternative garde les deux formes.123ROW_RE = re.compile(124 r"(\d)\s*½\s*·\s*(\d)\s*chambres?"125 r"\s*([\d\s]*?)\s*pi²"126 r"\s*([\d\s]+?)\s*\$\s*/\s*mois"127 r"\s*(Libre.*?)\s*(?:Photos\s+et\s+plan|Plan)\b", re.S)128# 2026-10-25 : Cloudflare sert PARFOIS la variante ANGLAISE à l'URL française129# (cache sans Vary, clé de cache qui IGNORE la query string — le cache-buster130# ?lkb= ne buste donc rien). Même data-count=8 mais « 2 bedroom · 4½ 875 sq ft131# $2,140 a month Free now Photos and plan » → 0/8 pour ROW_RE. On parse les132# deux langues (données identiques) et on renormalise la dispo en français.133ROW_EN_RE = re.compile(134 r"(\d)\s*bedrooms?\s*·\s*(\d)\s*½"135 r"\s*([\d,\s]*?)\s*sq\s*ft"136 r"\s*\$\s*([\d,\s]+?)\s*(?:a|per)\s+month"137 r"\s*(Free.*?)\s*(?:Photos\s+and\s+plan|Plan)\b", re.S)138IMG_RE = re.compile(r'<img[^>]+src="([^"]+\.webp)"', re.I)139140_EN_MONTHS = {"jan": "janvier", "feb": "février", "mar": "mars",141 "apr": "avril", "may": "mai", "jun": "juin", "jul": "juillet",142 "aug": "août", "sep": "septembre", "oct": "octobre",143 "nov": "novembre", "dec": "décembre"}144145146def _avail_fr(avail: str) -> str:147 """« Free now » / « Free on Nov 1, 2026 » → texte français canonique."""148 if re.match(r"free\s+now", avail, re.I):149 return "Libre maintenant"150 m = re.match(r"free\s+on\s+([A-Za-z]+)\.?\s+(\d{1,2}),?\s+(\d{4})",151 avail, re.I)152 if m:153 month = _EN_MONTHS.get(m.group(1)[:3].lower())154 if month:155 day = int(m.group(2))156 jour = "1er" if day == 1 else str(day)157 return f"Libre le {jour} {month} {m.group(3)}"158 return avail159160161def _flat(fragment: str) -> str:162 text = _html.unescape(fragment)163 text = re.sub(r"<[^>]+>", " ", text)164 return re.sub(r"\s+", " ", text).strip()165166167class SolarisConnector(BaseConnector):168 source_id = "solaris"169 request_delay = 0.6170 max_images = 10171172 def _enable_residential_proxy(self) -> bool:173 """Route toute la session via Oxylabs résidentiel CA (session collante)."""174 endpoint = os.environ.get("OXYLABS_PROXY")175 user = os.environ.get("OXYLABS_PROXY_USER")176 pwd = os.environ.get("OXYLABS_PROXY_PASS")177 if not (endpoint and user and pwd):178 return False179 puser = f"{user}-cc-CA-sessid-solaris{time.time_ns()}-sesstime-10"180 proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"181 self.session.proxies = {"http": proxy, "https": proxy}182 self.session.verify = False # CA MITM du proxy Oxylabs (cf. _resilient)183 return True184185 def _ensure_session_route(self) -> None:186 # 2026-10-24 : le Cloudflare du site tarpite l'IP du nœud (connexion187 # acceptée, aucune réponse, même sur la racine). base.get() escalade188 # alors HORS session (_resilient) — invisible pour l'enregistrement189 # des fixtures et ~30 s perdues par sync. Sonde courte ; au timeout,190 # toute la session bascule sur une IP résidentielle CA collante191 # (patron boreal 763a8ca / citiluxx).192 if self.session.proxies:193 return194 try:195 self.session.get(BASE + "/", timeout=12)196 return197 except (requests.ConnectionError, requests.Timeout):198 pass199 except Exception:200 return # rejeu des fixtures (MissingFixture) → rester direct201 self._enable_residential_proxy()202203 def fetch(self) -> list[Listing]:204 self._ensure_session_route()205 # Le serveur sert PARFOIS la page avec l'en-tête « N unités libres »206 # (data-count>0) mais une liste d'unités vide/tronquée — hoquets207 # constatés 2026-10-16 et 2026-10-19. Retry avec cache-buster208 # (site derrière Cloudflare, pattern du fix brio 2c52899) avant de209 # lever l'erreur franche. Cache-buster seulement sur les tentatives210 # 2-3 : la clé de rejeu des fixtures reste l'URL nue.211 last_err: RuntimeError | None = None212 for attempt in range(3):213 if attempt:214 time.sleep(4 * attempt)215 if self.session.proxies:216 # le cache CF ignore la query string → le vrai levier de217 # retry est une NOUVELLE IP collante (autre sortie/colo).218 self._enable_residential_proxy()219 url = PLANS_URL if attempt == 0 else \220 f"{PLANS_URL}?lkb={int(time.time())}"221 try:222 return self._fetch_once(url)223 except RuntimeError as err:224 last_err = err225 raise last_err226227 def _fetch_once(self, url: str) -> list[Listing]:228 # le serveur n'annonce pas de charset → requests décoderait en229 # latin-1 et casserait « ½ », « ² » et les espaces insécables des prix.230 raw = self.get(url).content.decode("utf-8", "replace")231232 m = SECTION_RE.search(raw)233 if not m:234 # gabarit remanié ≠ vrai zéro (pattern sotramont) : jamais de235 # zéro silencieux quand la section des unités a disparu.236 raise RuntimeError(237 "solaris: section data-live=\"units\" introuvable sur "238 f"{PLANS_URL} — gabarit du site modifié ?")239 section = m.group(0)240241 cm = COUNT_RE.search(section)242 count = int(cm.group(1)) if cm else None243244 # images : plans/photos des unités (le n° d'unité figure dans le nom245 # de fichier des plans) + photos génériques du projet (variante -md).246 all_imgs = [u if u.startswith("http") else BASE + u247 for u in dict.fromkeys(IMG_RE.findall(raw))]248 plan_imgs = [u for u in all_imgs if "/plans/unites-" in u]249 building_imgs = [u for u in all_imgs250 if "/photos/" in u and "-md.webp" in u]251252 listings: list[Listing] = []253 for num, body in UNIT_LI_RE.findall(section):254 text = _flat(body)255 row = ROW_RE.search(text)256 if row:257 n, beds, sqft, amount, avail = row.groups()258 else:259 row = ROW_EN_RE.search(text)260 if not row:261 continue262 beds, n, sqft, amount, avail = row.groups()263 avail = _avail_fr(avail)264 try:265 price = float(re.sub(r"[\s,]", "", amount))266 except ValueError:267 continue268 if not 300 <= price <= 20000:269 continue270 unit_type = f"{n}½"271 area = None272 sqft = re.sub(r"[\s,]", "", sqft)273 if sqft.isdigit():274 area = float(sqft)275 imgs = [u for u in plan_imgs276 if num in re.findall(r"\d{3}", u.rsplit("/", 1)[-1])]277 imgs += building_imgs278 listings.append(Listing(279 source=self.source_id,280 external_id=f"solaris-{num}",281 url=f"{PLANS_URL}#dispo-liste",282 title=f"Solaris Boisbriand — {unit_type} (unité {num})",283 address=ADDRESS,284 city=CITY,285 unit_type=unit_type,286 bedrooms=float(beds),287 price=price,288 price_label=f"{int(price)} $/mois",289 availability=avail,290 area_sqft=area,291 description=f"Appartement {unit_type} ({beds} chambre(s)),"292 f" unité {num}, au Solaris, Faubourg Boisbriand.",293 details={"unit": num},294 images=list(dict.fromkeys(imgs))[: self.max_images],295 ))296297 if not listings and (count is None or count > 0):298 raise RuntimeError(299 "solaris: aucune unité parsée alors que la page annonce "300 f"data-count={count!r} — parsing cassé ?")301 return listings302