Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/fb_marketplace.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-2313# Last Modified : 2026-08-2314#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/fb_marketplace.py : Facebook Marketplace (propriétés à vendre)91# via l'acteur Apify maison gorgeous_thistle/ka-fb-immo (jumeau « vente »92# de ka-fb-marketplace utilisé par Lou-Ka pour les locations).93#94# L'acteur scrape le Marketplace public DÉCONNECTÉ (JSON préchargé du HTML,95# proxy résidentiel CA) : phase recherche (33 villes × tranches de prix)96# puis fiches détail (GPS, adresse civique, description, galerie complète,97# statut vendu/retiré). Particularité de la source : le flux de recherche est98# trié par date de création (~25 annonces/URL), une annonce en disparaît donc99# en quelques jours alors qu'elle est toujours en vente. Le connecteur100# maintient donc les fiches actives par RE-VÉRIFICATION tournante101# (extraDetailIds, rotation par ancienneté du cache) : toujours en vente →102# conservée, vendue/retirée → disparaît (délai de grâce standard).103#104# ⚠️ Loi 25 : l'acteur n'extrait PAS le vendeur (nom/téléphone) — les champs105# broker_* restent vides pour cette source.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import json110import re111import time112from urllib.parse import quote113114import requests115116from .base import BaseConnector117from ._resilient import _secret118from ..schema import PropertyListing119120APIFY_API = "https://api.apify.com/v2"121ACTOR = "gorgeous_thistle~ka-fb-immo"122123DETAIL_KEY = "v1" # bump = re-parse de toutes les fiches124MAX_DETAILS = 600 # budget fiches détail par run (nouveautés + recheck)125RECHECK_BUDGET = 300 # dont : re-vérifications d'annonces actives126MIN_INTERVAL_S = 3 * 3600 # entre deux runs Apify : rejouer la BD (annonces FB127 # peu volatiles ; épargne compute + bande passante)128RUN_TIMEOUT_S = 45 * 60129MIN_PRICE = 20000 # sous ce prix : appâts « contactez-moi » / loyers130131_MLS_RE = re.compile(r"(?:centris|mls)\D{0,12}(\d{7,10})", re.I)132_DIGIT_RE = re.compile(r"\d")133134135class FbMarketplaceConnector(BaseConnector):136 source_id = "fb_marketplace"137 use_detail_cache = False # cache géré manuellement (batch via l'acteur)138139 # -- API Apify (accès direct : pas la chaîne anti-bot des sites cibles) ---140 def _apify(self, method: str, path: str, token: str, **kw):141 r = requests.request(method, f"{APIFY_API}{path}",142 headers={"Authorization": f"Bearer {token}"},143 timeout=120, **kw)144 r.raise_for_status()145 return r.json()146147 def _proxy_template(self) -> str | None:148 """Gabarit Oxylabs résidentiel CA ({session} = session collante) —149 même mécanique que les runs de prod de ka-fb-marketplace (le proxy150 Apify se fait servir le mur de login sur les fiches détail)."""151 endpoint = _secret("OXYLABS_PROXY")152 user = _secret("OXYLABS_PROXY_USER")153 pwd = _secret("OXYLABS_PROXY_PASS")154 if not (endpoint and user and pwd):155 return None156 endpoint = endpoint.replace("http://", "")157 return (f"http://{user}-cc-CA-sessid-{{session}}:"158 f"{quote(pwd, safe='')}@{endpoint}")159160 def _run_actor(self, token: str, run_input: dict) -> list[dict]:161 """Démarre un run, attend la fin, retourne les items du dataset."""162 run = self._apify(163 "POST", f"/acts/{ACTOR}/runs?memory=2048&timeout=3000",164 token, json=run_input)["data"]165 run_id = run["id"]166 t0 = time.time()167 status = run["status"]168 while status in ("READY", "RUNNING"):169 if time.time() - t0 > RUN_TIMEOUT_S:170 self._apify("POST", f"/actor-runs/{run_id}/abort", token)171 raise RuntimeError(f"run Apify {run_id} : délai dépassé")172 time.sleep(20)173 run = self._apify("GET", f"/actor-runs/{run_id}", token)["data"]174 status = run["status"]175 if status != "SUCCEEDED":176 raise RuntimeError(f"run Apify {run_id} : statut {status}")177 ds = run["defaultDatasetId"]178 items, offset = [], 0179 while True:180 page = self._apify(181 "GET", f"/datasets/{ds}/items?clean=true&format=json"182 f"&limit=1000&offset={offset}", token)183 items.extend(page)184 if len(page) < 1000:185 return items186 offset += 1000187188 # -- reconstruction depuis la BD (replay/rechecks) -------------------------189 def _row_to_listing(self, row) -> PropertyListing:190 return PropertyListing(191 source=self.source_id, external_id=row["external_id"],192 url=row["url"] or "", title=row["title"] or "",193 address=row["address"] or "", sector=row["sector"] or "",194 city=row["city"] or "", region=row["region"] or "",195 property_type=row["property_type"] or "", price=row["price"],196 price_label=row["price_label"] or "", bedrooms=row["bedrooms"],197 bathrooms=row["bathrooms"], powder_rooms=row["powder_rooms"],198 area_sqft=row["area_sqft"], lot_sqft=row["lot_sqft"],199 year_built=row["year_built"], mls=row["mls"] or "",200 status=row["status"] or "a-vendre",201 description=row["description"] or "",202 features=json.loads(row["features"] or "[]"),203 details=json.loads(row["details"] or "{}"),204 images=json.loads(row["images"] or "[]"),205 lat=row["lat"], lng=row["lng"])206207 # -- mapping recherche + détail -> PropertyListing --------------------------208 def _make_listing(self, lid: str, obj: dict, det: dict) -> PropertyListing:209 unit = det.get("unit_fields") or []210 addr = (det.get("address") or "").strip()211 if not _DIGIT_RE.search(addr):212 addr = "" # « Sainte-Claire, QC » n'est pas civique213 desc = det.get("description") or ""214 mls = ""215 m = _MLS_RE.search(desc)216 if m:217 mls = m.group(1)218 details: dict = {}219 for k_src, k_dst in (("category_name", "Catégorie Marketplace"),220 ("listed_text", "Publication"),221 ("external_url", "Lien externe"),222 ("virtual_tour_url", "Visite virtuelle"),223 ("postal_code", "Code postal (RTA)"),224 ("walk_score", "Walk Score"),225 ("transit_score", "Transit Score"),226 ("bike_score", "Bike Score")):227 if det.get(k_src) not in (None, ""):228 details[k_dst] = det[k_src]229 images = det.get("images") or []230 if not images and obj.get("primary_photo"):231 images = [obj["primary_photo"]]232 city = (det.get("city") or obj.get("city") or "").strip()233 return PropertyListing(234 source=self.source_id, external_id=lid,235 url=obj.get("url") or f"https://www.facebook.com/marketplace/item/{lid}/",236 title=obj.get("title") or "",237 address=addr, city=city,238 property_type=(unit[0] if unit else obj.get("title") or ""),239 price=obj.get("price"),240 price_label=(f"{int(obj['price']):,} $".replace(",", " ")241 if obj.get("price") else ""),242 mls=mls, description=desc,243 features=[f.replace("\xa0", " ") for f in unit],244 details=details, images=images,245 lat=det.get("lat"), lng=det.get("lng"))246247 # -- contrat ----------------------------------------------------------------248 def fetch(self) -> list[PropertyListing]:249 from .. import db250 con = db.connect()251252 active = {r["external_id"]: r for r in con.execute(253 "SELECT * FROM listings WHERE source=? AND active=1",254 (self.source_id,)).fetchall()}255256 # throttle : entre deux runs Apify, rejouer l'état connu (aucun réseau).257 # La date du dernier VRAI run = MAX(fetched_at) du cache détail (les258 # replays n'y écrivent pas, contrairement à sync_log).259 last = con.execute(260 "SELECT MAX(fetched_at) ts FROM detail_cache WHERE source=?",261 (self.source_id,)).fetchone()262 if last and last["ts"] and time.time() - last["ts"] < MIN_INTERVAL_S \263 and active:264 print(f"[immo-ka] fb_marketplace: replay BD "265 f"({len(active)} actives, prochain run Apify dans "266 f"{(MIN_INTERVAL_S - time.time() + last['ts']) / 60:.0f} min)")267 return [self._row_to_listing(r) for r in active.values()]268269 token = _secret("APIFY_TOKEN")270 if not token:271 raise RuntimeError("APIFY_TOKEN manquant (voir ~/.claude/.env)")272273 cache = {r["external_id"]: r for r in con.execute(274 "SELECT external_id, key, fetched_at FROM detail_cache WHERE source=?",275 (self.source_id,)).fetchall()}276277 # re-vérification tournante des annonces actives : les plus anciennes278 # au cache d'abord (fetched_at) — vivantes → conservées, parties → non279 recheck = sorted(280 (i for i in active if i in cache),281 key=lambda i: cache[i]["fetched_at"] or 0)[:RECHECK_BUDGET]282 recheck_set = set(recheck)283 skip = [i for i, r in cache.items()284 if r["key"] == DETAIL_KEY and i not in recheck_set]285286 run_input: dict = {287 "getDetails": True, "maxDetails": MAX_DETAILS,288 "skipDetailIds": skip, "extraDetailIds": recheck,289 }290 tpl = self._proxy_template()291 if tpl:292 run_input["proxyUrlTemplate"] = tpl293294 items = self._run_actor(token, run_input)295 search = {i["id"]: i for i in items if i.get("kind") == "listing"}296 fresh = {i["id"]: {k: v for k, v in i.items()297 if k not in ("kind", "id", "ok")}298 for i in items if i.get("kind") == "detail" and i.get("ok")}299 print(f"[immo-ka] fb_marketplace: {len(search)} en recherche, "300 f"{len(fresh)} fiches détail, {len(recheck)} re-vérifications")301302 for lid, payload in fresh.items(): # mémoriser (nopdp inclus)303 db.put_cached_detail(con, self.source_id, lid, DETAIL_KEY, payload)304305 out: list[PropertyListing] = []306 emitted: set[str] = set()307308 # 1) flux de recherche (nouveautés + annonces récentes)309 for lid, obj in search.items():310 st = (obj.get("state") or "").strip().lower()311 if st and st not in ("qc", "quebec", "québec"):312 continue313 if obj.get("is_sold") or obj.get("is_pending"):314 continue315 price = obj.get("price")316 if not price or price < MIN_PRICE:317 continue318 det = fresh.get(lid)319 if det is None:320 det = db.get_stale_detail(con, self.source_id, lid) or {}321 elif det.get("gone"):322 continue # verdict frais : vendue/retirée323 out.append(self._make_listing(lid, obj, det))324 emitted.add(lid)325326 # 2) annonces actives sorties du flux de recherche (tri par création) :327 # re-vérifiées ce run → verdict frais ; sinon rejouées telles quelles328 # en attendant leur tour de rotation329 for lid, row in active.items():330 if lid in emitted:331 continue332 det = fresh.get(lid)333 if det is not None and det.get("gone"):334 continue # vendue/retirée : délai de grâce puis retrait335 if det is not None and det.get("nopdp"):336 continue # fiche supprimée (mur permanent)337 lst = self._row_to_listing(row)338 if det: # rafraîchir les champs riches339 if det.get("description"):340 lst.description = det["description"]341 if det.get("images"):342 lst.images = det["images"]343 if det.get("lat") and det.get("lng"):344 lst.lat, lst.lng = det["lat"], det["lng"]345 out.append(lst)346 emitted.add(lid)347 return out348