codomo-alerts 0.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
codomo_alerts/demo.py ADDED
@@ -0,0 +1,128 @@
1
+ """Sample data so the dashboard can be tried without contacting Codomo."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import random
7
+ import shutil
8
+ import tempfile
9
+ from datetime import timedelta
10
+ from pathlib import Path
11
+
12
+ from .config import Config, Search
13
+ from .dashboard import overview, static_file
14
+ from .search import Listing
15
+ from .store import Store, iso, utcnow
16
+
17
+ STREETS = ["Parklaan", "Kanaalstraat", "Stationsplein", "Molenweg", "Havenkade", "Lindelaan",
18
+ "Torenstraat", "Brugstraat", "Singelpark", "Vondelkade", "Lichttoren", "Dijkgraaf"]
19
+ CITIES = ["Eindhoven", "Rotterdam", "Amsterdam"]
20
+ PRICES = {0: (780, 1250), 1: (1150, 1795)}
21
+ DEMO_URL = "https://codomo.eu/homes/nl/en"
22
+
23
+
24
+ def demo_config() -> Config:
25
+ cfg = Config()
26
+ cfg.search = Search(cities=CITIES, bedrooms=list(PRICES), price_max=1800, contracts=["indefinite", "2y", "1y"])
27
+ return cfg
28
+
29
+
30
+ def _home(rng: random.Random, pid: int, status: str = "available") -> Listing:
31
+ bedrooms = rng.choice(list(PRICES))
32
+ lo, hi = PRICES[bedrooms]
33
+ street = rng.choice(STREETS)
34
+ return Listing(id=f"demo-{pid}", name=f"{street} {rng.randint(1, 240)}{rng.choice(['', '', '-A', '-B', ' K2'])}",
35
+ url=DEMO_URL, price=float(rng.randrange(lo, hi, 5)), status=status,
36
+ city=rng.choice(CITIES), bedrooms=bedrooms, contract=rng.choice(["indefinite"] * 3 + ["2y"]),
37
+ furnishing=rng.choice(["fully-furnished", "furnished", "furnished", "semi-furnished"]),
38
+ interest=rng.randint(8, 120) if status == "interest" else None)
39
+
40
+
41
+ def _release_time(rng: random.Random, days_ago: int):
42
+ now = utcnow()
43
+ day = now - timedelta(days=days_ago)
44
+ if rng.random() < 0.2:
45
+ hour, minute = 22, rng.randint(15, 22) # 00:15 in Amsterdam is 22:15 or 23:15 UTC
46
+ else:
47
+ hour = rng.choice([7, 7, 8, 8, 8, 10, 10, 11, 13, 13, 14, 15])
48
+ minute = rng.randint(0, 59)
49
+ t = day.replace(hour=hour, minute=minute, second=rng.randint(0, 59), microsecond=0)
50
+ while t.weekday() >= 5 and rng.random() < 0.85:
51
+ t -= timedelta(days=1)
52
+ return min(t, now - timedelta(minutes=3))
53
+
54
+
55
+ def fill(store: Store, seed: int = 7) -> None:
56
+ rng = random.Random(seed)
57
+ now = utcnow()
58
+ pid = 1000
59
+ history = []
60
+ for days_ago in range(30, 0, -1):
61
+ for _ in range(rng.choice([0, 1, 1, 2, 3])):
62
+ pid += 1
63
+ history.append((_release_time(rng, days_ago), _home(rng, pid)))
64
+ history.sort(key=lambda h: h[0])
65
+ for at, x in history:
66
+ store.activate(x, at, new_period=True)
67
+ store.event("new", x.id, "available", x.price, at=at, notified=True)
68
+ minutes = int(rng.choice([rng.uniform(1, 15), rng.uniform(10, 90), rng.uniform(60, 600)]))
69
+ gone = at + timedelta(minutes=minutes)
70
+ if gone < now:
71
+ store.x("UPDATE listings SET last_seen=? WHERE id=?", (iso(gone), x.id))
72
+ store.gone(x.id, gone)
73
+ store.event("gone", x.id, "available", x.price, str(minutes * 60), at=gone)
74
+
75
+ for minutes_ago in (4, 38, 95, 180, 260, 410):
76
+ pid += 1
77
+ x = _home(rng, pid)
78
+ at = now - timedelta(minutes=minutes_ago)
79
+ store.activate(x, at, new_period=True)
80
+ store.event("new", x.id, "available", x.price, at=at, notified=True)
81
+ back = _home(rng, pid + 1)
82
+ store.activate(back, now - timedelta(minutes=22), new_period=True)
83
+ store.event("back", back.id, "available", back.price, at=now - timedelta(minutes=22), notified=True)
84
+ pid += 2
85
+ for i in range(3):
86
+ x = _home(rng, pid + i, "interest")
87
+ store.activate(x, now - timedelta(days=2), new_period=True)
88
+ store.event("interest", x.id, "interest", x.price, at=now - timedelta(days=2), notified=True)
89
+
90
+ first = now - timedelta(days=60)
91
+ store.building("nl/rotterdam/oude-haven", "Oude Haven", "Rotterdam", DEMO_URL, first) # first scan, hidden
92
+ store.building("nl/amsterdam/noorderpark", "Noorderpark", "Amsterdam", DEMO_URL, now - timedelta(days=9))
93
+ store.building("nl/eindhoven/strijp-laan", "Strijp Laan", "Eindhoven", DEMO_URL, now - timedelta(days=3))
94
+ store.event("building", None, detail=json.dumps({"name": "Strijp Laan", "city": "Eindhoven", "url": DEMO_URL}),
95
+ at=now - timedelta(days=3))
96
+ store.set("status", {"state": "watching", "message": "", "last_check": iso(now),
97
+ "next_check": iso(now + timedelta(seconds=97)), "window": "release hours"})
98
+
99
+
100
+ def sample(seed: int = 7) -> tuple[Store, Config]:
101
+ store = Store(":memory:")
102
+ fill(store, seed)
103
+ return store, demo_config()
104
+
105
+
106
+ def export(directory: Path, seed: int = 7) -> Path:
107
+ """Write a static copy of the dashboard with sample data (used for the website demo)."""
108
+ store, cfg = sample(seed)
109
+ data = overview(store, cfg)
110
+ data["demo"] = True
111
+ directory.mkdir(parents=True, exist_ok=True)
112
+ (directory / "api").mkdir(exist_ok=True)
113
+ for name in ("index.html", "app.css", "app.js", "favicon.svg"):
114
+ (directory / name).write_bytes(static_file(name))
115
+ (directory / "api" / "overview.json").write_text(json.dumps(data), encoding="utf-8")
116
+ return directory
117
+
118
+
119
+ def temp_store(seed: int = 7) -> tuple[Store, Config, Path]:
120
+ folder = Path(tempfile.mkdtemp(prefix="codomo-demo-"))
121
+ store = Store(folder / "demo.sqlite3")
122
+ fill(store, seed)
123
+ return store, demo_config(), folder
124
+
125
+
126
+ def cleanup(folder: Path) -> None:
127
+ shutil.rmtree(folder, ignore_errors=True)
128
+
@@ -0,0 +1,86 @@
1
+ """MCP server: ask an AI assistant about Codomo homes. Run with `codomo-alerts mcp`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+
7
+ from . import catalog, messages
8
+ from .client import Client, CodomoError
9
+ from .config import Config, ConfigError, build
10
+ from .runtime import db_path
11
+ from .search import fetch
12
+ from .store import Store, to_listing
13
+
14
+ CACHE_SECONDS = 60
15
+ MAX_RESULTS = 25
16
+
17
+
18
+ def run(cfg: Config) -> None:
19
+ try:
20
+ from mcp.server.fastmcp import FastMCP
21
+ except ImportError:
22
+ raise SystemExit("The MCP server needs an extra: pip install 'codomo-alerts[mcp]'") from None
23
+
24
+ server = FastMCP("codomo")
25
+ client = Client(cfg.base_url, min_gap=2.0)
26
+ store = Store(db_path(cfg))
27
+ cache: dict[tuple, tuple[float, str]] = {}
28
+
29
+ @server.tool()
30
+ def search_homes(city: str = "", country: str = "", bedrooms: str = "", max_price: int = 0,
31
+ interest: bool = False) -> str:
32
+ """Codomo homes you can book directly right now (or register interest for, with interest=true:
33
+ Codomo then picks someone from the shortlist).
34
+
35
+ city: a city name like "Eindhoven", "The Hague", "Granada", "Lisbon" or "Linz", empty for every city.
36
+ country: Netherlands, Spain, Portugal or Austria, empty for every country.
37
+ bedrooms: studio, 1, 2, 3, 4 or "2+", empty for any.
38
+ max_price: monthly price in euro with service costs, 0 for no limit.
39
+ """
40
+ key = (city.strip().lower(), country.strip().lower(), bedrooms.strip().lower(), max_price, interest)
41
+ hit = cache.get(key)
42
+ if hit and time.monotonic() - hit[0] < CACHE_SECONDS:
43
+ return hit[1]
44
+ try:
45
+ search = build({"search": {"cities": city or [], "countries": country or [], "bedrooms": bedrooms or [],
46
+ "price_max": max_price or None}}, {}).search
47
+ except ConfigError as e:
48
+ return str(e)
49
+ status = "interest" if interest else "available"
50
+ try:
51
+ found = sorted(fetch(client, search, status).values(),
52
+ key=lambda x: x.price or 0)[:MAX_RESULTS]
53
+ for x in found:
54
+ store.known_details(x)
55
+ except CodomoError as e:
56
+ return f"Codomo didn't answer: {e}"
57
+ if not found:
58
+ text = "Nothing matches right now."
59
+ else:
60
+ lines = [f"{x.name} · {messages.facts(x)} · {messages.terms(x)}\n{x.url}" for x in found]
61
+ text = "\n\n".join(lines)
62
+ if interest:
63
+ text += f"\n\n{messages.SHORTLIST}"
64
+ cache[key] = (time.monotonic(), text)
65
+ return text
66
+
67
+ @server.tool()
68
+ def list_cities() -> str:
69
+ """Cities where Codomo has homes, by country."""
70
+ return "\n".join(f"{name}: " + ", ".join(c for c, m in catalog.CITIES.items() if m == code)
71
+ for code, name in catalog.MARKETS.items())
72
+
73
+ @server.tool()
74
+ def recent_activity(limit: int = 15) -> str:
75
+ """What the local watcher saw lately: new homes, homes taken, register-interest homes."""
76
+ rows = store.q("""SELECT e.kind, e.at, e.detail, l.* FROM events e JOIN listings l ON l.id = e.listing_id
77
+ ORDER BY e.id DESC LIMIT ?""", (max(1, min(limit, 100)),))
78
+ if not rows:
79
+ return "No activity recorded. Start the watcher with `codomo-alerts watch` first."
80
+ out = []
81
+ for r in rows:
82
+ x = to_listing(r)
83
+ out.append(f"{r['at'][:16].replace('T', ' ')} UTC {r['kind']}: {x.name} · {messages.facts(x)}")
84
+ return "\n".join(out)
85
+
86
+ server.run()
@@ -0,0 +1,109 @@
1
+ """The words people read: notification titles and bodies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+
7
+ from . import PROJECT_URL, schedule
8
+ from .search import Listing
9
+
10
+ DIGEST_LIMIT = 10
11
+ SHORTLIST = "Not first come: register your interest on codomo.eu, Codomo picks someone from the shortlist"
12
+
13
+
14
+ def money(value: float | None) -> str:
15
+ if value is None:
16
+ return ""
17
+ return f"€{value:,.0f}" if value == int(value) else f"€{value:,.2f}"
18
+
19
+
20
+ def facts(x: Listing) -> str:
21
+ return " · ".join(p for p in (x.city_name, x.bedrooms_name, money(x.price)) if p)
22
+
23
+
24
+ def terms(x: Listing) -> str:
25
+ return " · ".join(p for p in (x.contract_name, x.furnishing_name, x.gender_name) if p)
26
+
27
+
28
+ def interested(x: Listing) -> str:
29
+ if x.interest is None:
30
+ return ""
31
+ return "1 person showed interest" if x.interest == 1 else f"{x.interest} people showed interest"
32
+
33
+
34
+ TITLES = {
35
+ "new": "{name}",
36
+ "back": "Back: {name}",
37
+ "bookable": "Now bookable: {name}",
38
+ "price": "Price drop: {name}",
39
+ "interest": "Register interest (shortlist): {name}",
40
+ }
41
+
42
+
43
+ def alert(kind: str, x: Listing, detail: str | None = None, now: datetime | None = None) -> tuple[str, str]:
44
+ lines = [facts(x)]
45
+ if kind == "price" and detail:
46
+ lines = [" · ".join(p for p in (x.city_name, x.bedrooms_name) if p),
47
+ f"{money(float(detail))} → {money(x.price)}"]
48
+ if terms(x):
49
+ lines.append(terms(x))
50
+ if kind == "interest":
51
+ lines.append(interested(x))
52
+ lines.append(SHORTLIST)
53
+ lines.append(x.url)
54
+ return TITLES[kind].format(name=x.name), "\n".join(line for line in lines if line)
55
+
56
+
57
+ def digest(items: list[tuple[str, Listing]], now: datetime | None = None) -> tuple[str, str]:
58
+ interest = all(kind == "interest" for kind, _ in items)
59
+ n = len(items)
60
+ if interest:
61
+ title = f"Register interest: {n} homes match"
62
+ elif all(kind == "new" for kind, _ in items):
63
+ title = f"{n} new homes"
64
+ else:
65
+ title = f"{n} homes to look at"
66
+ blocks = []
67
+ for kind, x in items[:DIGEST_LIMIT]:
68
+ label = "" if kind in ("new", "interest") else {"back": "Back: ", "bookable": "Now bookable: ",
69
+ "price": "Price drop: "}[kind]
70
+ extra = f" · {x.gender_name}" if x.gender_name else ""
71
+ if kind == "interest" and interested(x):
72
+ extra += f" · {interested(x)}"
73
+ blocks.append(f"{label}{x.name} · {facts(x)}{extra}\n{x.url}")
74
+ if n > DIGEST_LIMIT:
75
+ blocks.append(f"and {n - DIGEST_LIMIT} more")
76
+ if interest:
77
+ blocks.append(SHORTLIST)
78
+ return title, "\n\n".join(blocks)
79
+
80
+
81
+ def welcome(summary: str, matching: int) -> tuple[str, str]:
82
+ homes = "1 home matches" if matching == 1 else f"{matching} homes match"
83
+ return "Watching Codomo", f"{summary}\n{homes} right now. You'll get a message when a new one shows up."
84
+
85
+
86
+ def search_changed(summary: str, matching: int) -> tuple[str, str]:
87
+ homes = "1 home matches" if matching == 1 else f"{matching} homes match"
88
+ return "Search updated", f"{summary}\n{homes} right now."
89
+
90
+
91
+ def paused(reason: str, until: datetime) -> tuple[str, str]:
92
+ return "Alerts paused", f"{reason}. Trying again at {schedule.local(until):%H:%M}."
93
+
94
+
95
+ def resumed() -> tuple[str, str]:
96
+ return "Alerts back on", "Codomo answers again."
97
+
98
+
99
+ def broken(reason: str) -> tuple[str, str]:
100
+ return "Alerts may be broken", f"{reason}. Check for an update: {PROJECT_URL}/releases"
101
+
102
+
103
+ def building(name: str, city: str, url: str | None = None) -> tuple[str, str]:
104
+ where = " · ".join(p for p in (city, "new on codomo.eu") if p)
105
+ return f"New building: {name}", "\n".join(p for p in (where, url) if p)
106
+
107
+
108
+ def test() -> tuple[str, str]:
109
+ return "codomo-alerts", "Test message. Notifications work."
@@ -0,0 +1,60 @@
1
+ """Send notifications through Apprise (Telegram, Discord, ntfy, Slack, email and many more)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+ import apprise
8
+
9
+ log = logging.getLogger("codomo_alerts")
10
+ logging.getLogger("apprise").setLevel(logging.WARNING)
11
+
12
+
13
+ def _short(url: str) -> str:
14
+ return url.split("?", 1)[0].rstrip("/")
15
+
16
+
17
+ def masked(url: str) -> str:
18
+ server = apprise.Apprise.instantiate(url)
19
+ if server is None:
20
+ return url.split("://", 1)[0] + "://…"
21
+ return _short(server.url(privacy=True))
22
+
23
+
24
+ class Notifier:
25
+ def __init__(self, urls: list[str]):
26
+ self.urls = urls
27
+ self.apprise = apprise.Apprise()
28
+ self.invalid = [u for u in urls if not self.apprise.add(u)]
29
+
30
+ @property
31
+ def enabled(self) -> bool:
32
+ return len(self.apprise) > 0
33
+
34
+ def send(self, title: str, body: str) -> bool:
35
+ if not self.enabled:
36
+ log.info("%s | %s", title, body.replace("\n", " | "))
37
+ return True
38
+ # Per channel: if one works and another is broken, the message counts as sent,
39
+ # so the working channel is not sent the same alert again.
40
+ delivered = False
41
+ for server in self.apprise:
42
+ try:
43
+ ok = bool(server.notify(title=title, body=body, body_format=apprise.NotifyFormat.TEXT))
44
+ except Exception: # a broken plugin must never stop the watcher
45
+ ok = False
46
+ if ok:
47
+ delivered = True
48
+ else:
49
+ log.warning("Couldn't send to %s", _short(server.url(privacy=True)))
50
+ return delivered
51
+
52
+ def test(self, title: str, body: str) -> list[tuple[str, bool]]:
53
+ results = [(masked(u), False) for u in self.invalid]
54
+ for server in self.apprise:
55
+ try:
56
+ ok = bool(server.notify(title=title, body=body, body_format=apprise.NotifyFormat.TEXT))
57
+ except Exception:
58
+ ok = False
59
+ results.append((_short(server.url(privacy=True)), ok))
60
+ return results
@@ -0,0 +1,62 @@
1
+ """Process plumbing: logging, the data folder and a single-instance lock."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from .config import Config
11
+
12
+
13
+ class AlreadyRunning(Exception):
14
+ pass
15
+
16
+
17
+ def setup_logging(level: str = "INFO") -> None:
18
+ logging.basicConfig(
19
+ level=getattr(logging, level.upper(), logging.INFO),
20
+ format="%(asctime)s %(message)s",
21
+ datefmt="%Y-%m-%d %H:%M:%S",
22
+ stream=sys.stdout,
23
+ )
24
+ for noisy in ("urllib3", "apprise", "mcp", "httpx"):
25
+ logging.getLogger(noisy).setLevel(logging.WARNING)
26
+
27
+
28
+ def db_path(cfg: Config) -> Path:
29
+ return cfg.data_dir / "codomo-alerts.sqlite3"
30
+
31
+
32
+ class Lock:
33
+ """Held while a watcher runs, so two of them never poll from the same data folder."""
34
+
35
+ def __init__(self, folder: Path):
36
+ folder.mkdir(parents=True, exist_ok=True)
37
+ self.path = folder / "watch.lock"
38
+ self.file = None
39
+
40
+ def __enter__(self):
41
+ self.file = open(self.path, "a+") # noqa: SIM115
42
+ try:
43
+ if os.name == "nt":
44
+ import msvcrt
45
+ self.file.seek(0)
46
+ msvcrt.locking(self.file.fileno(), msvcrt.LK_NBLCK, 1)
47
+ else:
48
+ import fcntl
49
+ fcntl.flock(self.file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
50
+ except OSError:
51
+ self.file.close()
52
+ raise AlreadyRunning(f"Another watcher already uses {self.path.parent}") from None
53
+ self.file.seek(0)
54
+ self.file.truncate()
55
+ self.file.write(str(os.getpid()))
56
+ self.file.flush()
57
+ return self
58
+
59
+ def __exit__(self, *exc):
60
+ if self.file:
61
+ self.file.close()
62
+ return False
@@ -0,0 +1,56 @@
1
+ """When to check. All times are Amsterdam time, whatever the server's clock zone is."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ from datetime import datetime, time
7
+ from zoneinfo import ZoneInfo
8
+
9
+ from .config import MIN_INTERVAL, Schedule
10
+
11
+ AMS = ZoneInfo("Europe/Amsterdam")
12
+
13
+ # Most homes are released on weekdays during office hours, plus a small batch just after
14
+ # midnight when unpaid reservations go back on sale (seen again on Codomo, 2026-11-16 00:16).
15
+ RELEASE_WINDOWS = [
16
+ (range(0, 5), time(8, 30), time(18, 0)),
17
+ (range(0, 7), time(0, 5), time(0, 45)),
18
+ ]
19
+ DAY = (time(7, 0), time(23, 30))
20
+
21
+
22
+ def local(now: datetime | None = None) -> datetime:
23
+ return (now or datetime.now(AMS)).astimezone(AMS)
24
+
25
+
26
+ def _within(t: time, start: time, end: time) -> bool:
27
+ return start <= t < end if start <= end else (t >= start or t < end)
28
+
29
+
30
+ def window(now: datetime | None = None) -> str:
31
+ n = local(now)
32
+ for days, start, end in RELEASE_WINDOWS:
33
+ if n.weekday() in days and _within(n.time(), start, end):
34
+ return "release hours"
35
+ if _within(n.time(), *DAY):
36
+ return "daytime"
37
+ return "night"
38
+
39
+
40
+ def _jitter(seconds: float, amount: float, rng: random.Random | None) -> float:
41
+ r = (rng or random).uniform(1 - amount, 1 + amount)
42
+ return max(MIN_INTERVAL, seconds * r)
43
+
44
+
45
+ def next_delay(s: Schedule, now: datetime | None = None, rng: random.Random | None = None) -> float:
46
+ base = {"release hours": s.hot, "daytime": s.day, "night": s.night}[window(now)]
47
+ return _jitter(base, s.jitter, rng)
48
+
49
+
50
+ def interest_due_every(s: Schedule) -> float:
51
+ """Register-interest homes have no deadline to race, so they are read less often."""
52
+ return max(MIN_INTERVAL, s.interest)
53
+
54
+
55
+ def quiet(hours: tuple[time, time] | None, now: datetime | None = None) -> bool:
56
+ return bool(hours) and _within(local(now).time(), *hours)