SPB Git

Repository Public

rentals_ca.py 11.5 KB 261 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/rentals_ca.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-08-1814#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/rentals_ca.py : Rentals.ca — portail locatif national, filtré91#   PROVINCE DE QUÉBEC. Même plateforme GraphQL que Louer.ca (mêmes City.id,92#   mutation acquireAuthInfo, clé publique `rentalsGqlKey` de window.appconf),93#   mais l'inventaire de marque est un peu plus large (~+15 % vérifié sur94#   Québec : 78 annonces contre 67 côté Louer.ca) — les doublons inter-marques95#   sont résorbés par la dédup (rentals_ca est dans la liste PORTALS).96#   ⚠️ rentals.ca est derrière Cloudflare (« Just a moment… ») : chaque appel97#   GraphQL est REJOUÉ via Scrapfly ASP SANS rendu JS (POST JSON, coût minime98#   par rapport à un render_js). Pour contenir le budget Scrapfly :99#     - villes limitées (LOUKA_RENTALSCA_CITIES) et plafond par ville ;100#     - pages de 200 annonces (1 à 4 requêtes liste par ville) ;101#     - détails PAR LOTS de 40 via nodes(ids:[…]) — 1 requête pour 40 fiches —102#       avec cache TTL : seuls les lots nouveaux/périmés sont re-téléchargés.103#   Régime de croisière : ~25-40 appels Scrapfly par synchronisation.104#   ⚠️ CGU Rentals.ca : extraction interdite sans accord écrit (même réserve105#   que louer_ca).106# -----------------------------------------------------------------------------107from __future__ import annotations108109import datetime110import json111import os112import re113114from ..schema import Listing115from . import _detailutil as du116from .louer_ca import LouerCaConnector117118# villes QC interrogées (slugs rentals.ca) — volontairement bornées : chaque119# page liste coûte un appel Scrapfly ASP120CITIES = [c.strip() for c in os.environ.get(121    "LOUKA_RENTALSCA_CITIES",122    "montreal,quebec-city,laval,gatineau,longueuil,sherbrooke,levis,"123    "trois-rivieres,saguenay,drummondville").split(",") if c.strip()]124125PAGE_SIZE = int(os.environ.get("LOUKA_RENTALSCA_PAGE_SIZE", "200"))126MAX_PER_CITY = int(os.environ.get("LOUKA_RENTALSCA_MAX_PER_CITY", "800"))127DETAIL_LIMIT = int(os.environ.get("LOUKA_RENTALSCA_DETAIL_LIMIT", "600"))128DETAIL_BATCH = int(os.environ.get("LOUKA_RENTALSCA_DETAIL_BATCH", "40"))129TTL_DAYS = float(os.environ.get("LOUKA_RENTALSCA_TTL_DAYS", "7"))130131132class RentalsCaConnector(LouerCaConnector):133    source_id = "rentals_ca"134    request_delay = 0.3            # entre appels Scrapfly (API, pas le site)135    home_url = "https://rentals.ca/"136    gql_url = "https://rentals.ca/graphql"137    site = "https://rentals.ca"138    fallback_key = "kJFM-mm4c-xg6B-qiwy"   # rentalsGqlKey publique (2026-08)139    page_size = PAGE_SIZE140    max_per_city = MAX_PER_CITY141142    # -- transport : tout passe par Scrapfly ASP (POST JSON, sans rendu JS) ----143    def _scrapfly_gql(self, query: str, variables: dict,144                      token: str | None = None) -> dict:145        headers = {"Content-Type": "application/json",146                   "Origin": self.site, "Referer": self.home_url}147        if token:148            headers["Authorization"] = f"Bearer {token}"149        res = self.scrapfly(self.gql_url, render_js=False, asp=True,150                            method="POST",151                            body=json.dumps({"query": query,152                                             "variables": variables}),153                            headers=headers)154        try:155            return json.loads(res.get("content") or "{}")156        except ValueError:157            return {}158159    def _ensure_token(self) -> None:160        import time as _time161        if self._token and _time.time() - self._token_time < 2700:162            return163        payload = self._scrapfly_gql(164            "mutation($k:String!){acquireAuthInfo(credentials:{apiKey:$k})"165            "{jwt status}}", {"k": self._api_key})166        auth = ((payload.get("data") or {}).get("acquireAuthInfo")) or {}167        jwt = auth.get("jwt")168        if isinstance(jwt, str) and jwt.startswith("{"):169            jwt = json.loads(jwt)170        token = jwt.get("accessToken") if isinstance(jwt, dict) else jwt171        if not token:172            # clé périmée ? la relire dans window.appconf de la page d'accueil173            home = self.get_scrapfly(self.home_url, render_js=False, asp=True)174            m = re.search(r'"rentalsGqlKey":\s*"([^"]+)"', home or "")175            if m:176                self._api_key = m.group(1)177                payload = self._scrapfly_gql(178                    "mutation($k:String!){acquireAuthInfo(credentials:"179                    "{apiKey:$k}){jwt status}}", {"k": self._api_key})180                auth = ((payload.get("data") or {})181                        .get("acquireAuthInfo")) or {}182                jwt = auth.get("jwt")183                if isinstance(jwt, str) and jwt.startswith("{"):184                    jwt = json.loads(jwt)185                token = (jwt.get("accessToken")186                         if isinstance(jwt, dict) else jwt)187        if not token:188            raise RuntimeError("Rentals.ca: handshake JWT échoué")189        self._token = token190        self._token_time = _time.time()191192    def _gql(self, query: str, variables: dict, auth: bool = True) -> dict:193        if auth:194            self._ensure_token()195        payload = self._scrapfly_gql(query, variables,196                                     token=self._token if auth else None)197        if payload.get("errors") and auth:198            msg = payload["errors"][0].get("message", "")199            if "AUTH" in msg.upper():          # jeton expiré : on réessaie200                self._token = ""201                self._ensure_token()202                payload = self._scrapfly_gql(query, variables,203                                             token=self._token)204        return payload.get("data") or {}205206    # -- détail par LOTS (1 requête Scrapfly pour DETAIL_BATCH fiches) ---------207    def _details_batch(self, gids: list[str]) -> dict[str, dict]:208        q = ("query($ids:[ID!]!){nodes(ids:$ids){... on RentalListing{"209             + self._DETAIL_FRAG + "}}}")210        out: dict[str, dict] = {}211        for node in self._gql(q, {"ids": gids}).get("nodes") or []:212            if isinstance(node, dict) and node.get("id"):213                out[node["id"]] = node214        return out215216    def fetch(self) -> list[Listing]:217        if not os.environ.get("SCRAPFLY_KEY"):218            raise RuntimeError("SCRAPFLY_KEY manquant (voir .env)")219        today = datetime.date.today().isoformat()220        cards: dict[str, tuple[dict, str]] = {}221        for slug in CITIES:222            cid = self._city_id(slug)223            if not cid:224                continue225            for card in self._city_listings(cid):226                gid = card.get("id")227                if gid:228                    cards.setdefault(gid, (card, slug))229230        # cache TTL : détails frais réutilisés sans trafic, le reste par lots231        cache = du.TtlDetailCache(self, budget=DETAIL_LIMIT, ttl_days=TTL_DAYS,232                                  key="v1", fetch_html=lambda gid: gid)233        details: dict[str, dict] = {}234        todo: list[str] = []235        out: list[Listing] = []236        try:237            for gid in cards:238                payload, fresh = cache.peek(gid)239                if payload is not None:240                    details[gid] = payload241                if not fresh and len(todo) < DETAIL_LIMIT:242                    todo.append(gid)243            for i in range(0, len(todo), DETAIL_BATCH):244                got = self._details_batch(todo[i:i + DETAIL_BATCH])245                for gid, node in got.items():246                    cache.put(gid, node)247                    details[gid] = node248249            for gid, (card, slug) in cards.items():250                node = details.get(gid) or {}251                region = (((node.get("address") or {}).get("city") or {})252                          .get("regionCode"))253                if region and region != "QC":254                    continue               # sécurité : Québec uniquement255                out.extend(self._card_listings(256                    card, node, today,257                    default_city=slug.replace("-", " ").title()))258        finally:259            cache.close()260        return out261
Files main
Menu

Theme