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.
@@ -0,0 +1,211 @@
1
+ (() => {
2
+ const SRC = document.body.dataset.src;
3
+ const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
4
+ const TAGS = {
5
+ new: "New", back: "Back", bookable: "Bookable", price: "Price drop",
6
+ interest: "Shortlist", gone: "Taken", building: "Building",
7
+ };
8
+ const HOT = new Set(["new", "back", "bookable", "price", "interest"]);
9
+ let data = null;
10
+
11
+ const $ = (id) => document.getElementById(id);
12
+ // A static demo keeps its timestamps fresh by moving them to the present.
13
+ const at = (iso) => Date.parse(iso) + (data && data.demo ? Date.now() - Date.parse(data.now) : 0);
14
+
15
+ function el(tag, cls, text) {
16
+ const node = document.createElement(tag);
17
+ if (cls) node.className = cls;
18
+ if (text !== undefined && text !== null) node.textContent = text;
19
+ return node;
20
+ }
21
+
22
+ const money = (v) => (v === null || v === undefined ? "" : "€" + Math.round(v).toLocaleString("en-US"));
23
+ const join = (parts) => parts.filter(Boolean).join(" · ");
24
+
25
+ function ago(iso) {
26
+ if (!iso) return "";
27
+ const s = Math.max(0, (Date.now() - at(iso)) / 1000);
28
+ if (s < 60) return "just now";
29
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
30
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
31
+ return `${Math.floor(s / 86400)}d ago`;
32
+ }
33
+
34
+ function clock(iso) {
35
+ const d = new Date(at(iso));
36
+ const time = d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
37
+ const today = new Date().toDateString() === d.toDateString();
38
+ return today ? time : `${d.toLocaleDateString([], { weekday: "short" })} ${time}`;
39
+ }
40
+
41
+ function duration(minutes) {
42
+ if (minutes === null || minutes === undefined) return null;
43
+ if (minutes < 60) return `${minutes} min`;
44
+ if (minutes < 60 * 48) return `${Math.round(minutes / 60)} h`;
45
+ return `${Math.round(minutes / 1440)} days`;
46
+ }
47
+
48
+ function countdown(iso) {
49
+ const s = Math.round((at(iso) - Date.now()) / 1000);
50
+ if (s <= 0) return "now";
51
+ const m = Math.floor(s / 60);
52
+ return m >= 60 ? `${Math.floor(m / 60)}h ${m % 60}m` : `${m}:${String(s % 60).padStart(2, "0")}`;
53
+ }
54
+
55
+ function renderState() {
56
+ const pill = $("state");
57
+ const st = (data && data.status) || {};
58
+ const label = pill.querySelector("span");
59
+ pill.classList.toggle("on", st.state === "watching");
60
+ if (!data) { label.textContent = "Can't reach the watcher"; return; }
61
+ if (data.demo) { pill.classList.add("on"); label.textContent = "Demo · sample data"; return; }
62
+ if (st.state === "watching" && st.next_check) {
63
+ label.textContent = `Watching · next check ${countdown(st.next_check)}`;
64
+ } else if (st.state === "paused" || st.state === "retrying") {
65
+ const when = st.next_check ? ` · again at ${clock(st.next_check)}` : "";
66
+ label.textContent = `${st.state === "paused" ? "Paused" : "Retrying"}${when}`;
67
+ pill.title = st.message || "";
68
+ } else if (st.state === "stopped") {
69
+ label.textContent = "Stopped";
70
+ } else {
71
+ label.textContent = "Starting";
72
+ }
73
+ }
74
+
75
+ function stat(label, value, fallback) {
76
+ const box = el("div", "glass stat");
77
+ box.append(el("small", null, label));
78
+ box.append(value === null ? el("strong", "none", fallback) : el("strong", null, value));
79
+ return box;
80
+ }
81
+
82
+ function homeRow(h, extra) {
83
+ const li = el("li");
84
+ const a = el("a");
85
+ a.href = h.url; a.target = "_blank"; a.rel = "noopener";
86
+ const left = el("div");
87
+ left.append(el("div", "name", h.name));
88
+ left.append(el("div", "meta", join([h.city, h.bedrooms, h.contract, h.furnishing, h.gender])));
89
+ const right = el("div", "side");
90
+ right.append(el("div", "price", money(h.price)));
91
+ right.append(el("div", "when", extra || ago(h.since)));
92
+ a.append(left, right);
93
+ li.append(a);
94
+ return li;
95
+ }
96
+
97
+ function fill(list, items, make, empty) {
98
+ list.replaceChildren(...items.map(make));
99
+ if (!items.length) list.append(el("p", "empty", empty));
100
+ }
101
+
102
+ function renderHeat() {
103
+ const box = $("heat");
104
+ const cells = [el("b")];
105
+ for (let h = 0; h < 24; h++) cells.push(el("b", "h", h % 6 === 0 ? String(h).padStart(2, "0") : ""));
106
+ const max = Math.max(1, ...data.heatmap.flat());
107
+ data.heatmap.forEach((row, d) => {
108
+ cells.push(el("b", null, DAYS[d]));
109
+ row.forEach((n, h) => {
110
+ const cell = el("i");
111
+ if (n) cell.style.background = `color-mix(in srgb, var(--fg) ${Math.round(15 + 70 * (n / max))}%, transparent)`;
112
+ cell.title = `${DAYS[d]} ${String(h).padStart(2, "0")}:00 · ${n}`;
113
+ cells.push(cell);
114
+ });
115
+ });
116
+ box.replaceChildren(...cells);
117
+ const total = data.heatmap.flat().reduce((a, b) => a + b, 0);
118
+ box.nextElementSibling?.remove();
119
+ if (!total) box.after(el("p", "heat-note", "Fills in as new homes appear."));
120
+ }
121
+
122
+ function render() {
123
+ renderState();
124
+ $("search").textContent = data.search.summary;
125
+ document.title = `${data.stats.matching} · codomo alerts`;
126
+ $("version").textContent = `v${data.version}`;
127
+
128
+ const s = data.stats;
129
+ $("stats").replaceChildren(
130
+ stat("Matching now", String(s.matching)),
131
+ stat("New this week", String(s.new_week)),
132
+ stat("Taken this week", String(s.gone_week)),
133
+ stat("Typical time listed", duration(s.median_minutes), "No data yet"),
134
+ );
135
+
136
+ $("available-count").textContent = data.available.length ? String(data.available.length) : "";
137
+ fill($("available"), data.available, (h) => homeRow(h), "Nothing matches right now. You'll get a message when something does.");
138
+
139
+ $("interest-box").hidden = !data.interest.length;
140
+ fill($("interest"), data.interest, (h) => homeRow(h, h.interest === null || h.interest === undefined
141
+ ? "shortlist" : `${h.interest} interested`), "");
142
+
143
+ fill($("events"), data.events, (e) => {
144
+ const li = el("li");
145
+ li.append(el("span", `tag${HOT.has(e.kind) ? " hot" : ""}`, TAGS[e.kind] || e.kind));
146
+ const what = el("div", "what");
147
+ what.append(e.name || "");
148
+ let more = join([e.city, money(e.price)]);
149
+ if (e.kind === "gone" && /^\d+$/.test(e.detail || "")) more = join([e.city, `after ${duration(Math.round(e.detail / 60))}`]);
150
+ if (more) what.append(el("span", null, ` · ${more}`));
151
+ const time = el("time", null, clock(e.at));
152
+ time.dateTime = e.at;
153
+ li.append(what, time);
154
+ return li;
155
+ }, "Quiet so far.");
156
+
157
+ renderHeat();
158
+
159
+ $("cities-box").hidden = data.cities.length < 2;
160
+ const top = Math.max(1, ...data.cities.map((c) => c.count));
161
+ fill($("cities"), data.cities, (c) => {
162
+ const li = el("li");
163
+ li.append(el("span", null, c.name), el("span", "muted", String(c.count)));
164
+ const bar = el("div", "bar");
165
+ const fillBar = el("span");
166
+ fillBar.style.width = `${(100 * c.count) / top}%`;
167
+ bar.append(fillBar);
168
+ li.append(bar);
169
+ return li;
170
+ }, "");
171
+
172
+ $("buildings-box").hidden = !data.buildings.length;
173
+ fill($("buildings"), data.buildings, (b) => {
174
+ const li = el("li");
175
+ const row = el(b.url ? "a" : "div", b.url ? null : "row");
176
+ if (b.url) { row.href = b.url; row.target = "_blank"; row.rel = "noopener"; }
177
+ const left = el("div");
178
+ left.append(el("div", "name", b.name), el("div", "meta", b.city));
179
+ row.append(left, el("div", "when", `seen ${ago(b.since)}`));
180
+ li.append(row);
181
+ return li;
182
+ }, "");
183
+ }
184
+
185
+ async function load() {
186
+ try {
187
+ const res = await fetch(SRC, { cache: "no-store" });
188
+ if (!res.ok) throw new Error(res.status);
189
+ data = await res.json();
190
+ render();
191
+ } catch (e) {
192
+ data = null;
193
+ renderState();
194
+ }
195
+ }
196
+
197
+ // The star pill goes away for good once it's closed or clicked.
198
+ const star = $("star");
199
+ const STAR_KEY = "codomo-alerts-star-hidden";
200
+ const hideStar = () => {
201
+ star.classList.add("gone");
202
+ try { localStorage.setItem(STAR_KEY, "1"); } catch (e) { /* private mode */ }
203
+ };
204
+ try { if (localStorage.getItem(STAR_KEY)) star.hidden = true; } catch (e) { /* private mode */ }
205
+ star.querySelector("button").addEventListener("click", hideStar);
206
+ star.querySelector("a").addEventListener("click", () => setTimeout(hideStar, 500));
207
+
208
+ load();
209
+ setInterval(load, 15000);
210
+ setInterval(() => data && renderState(), 1000);
211
+ })();
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#0b0b0c"/><path d="M8 15.2 16 8l8 7.2V24a1 1 0 0 1-1 1h-4.5v-5.5h-5V25H9a1 1 0 0 1-1-1z" fill="#f4f4f5"/></svg>
@@ -0,0 +1,75 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="color-scheme" content="dark light">
7
+ <title>codomo alerts</title>
8
+ <link rel="icon" href="favicon.svg" type="image/svg+xml">
9
+ <link rel="stylesheet" href="app.css">
10
+ </head>
11
+ <body data-src="api/overview.json">
12
+ <div class="backdrop" aria-hidden="true"><span></span><span></span><span></span></div>
13
+
14
+ <main>
15
+ <header class="top">
16
+ <a class="brand" id="home" href="#">
17
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 11.2 12 4l8 7.2V20a1 1 0 0 1-1 1h-4.5v-5.5h-5V21H5a1 1 0 0 1-1-1z"/></svg>
18
+ <span>codomo <b>alerts</b></span>
19
+ </a>
20
+ <div class="pill" id="state"><i></i><span>Loading</span></div>
21
+ </header>
22
+
23
+ <p class="search" id="search"></p>
24
+
25
+ <section class="stats" id="stats"></section>
26
+
27
+ <section class="glass">
28
+ <div class="head"><h2>Available now</h2><span class="muted" id="available-count"></span></div>
29
+ <ul class="list" id="available"></ul>
30
+ </section>
31
+
32
+ <section class="glass" id="interest-box" hidden>
33
+ <div class="head"><h2>Register interest</h2><span class="muted">Codomo picks from the shortlist</span></div>
34
+ <ul class="list" id="interest"></ul>
35
+ </section>
36
+
37
+ <div class="grid">
38
+ <section class="glass">
39
+ <div class="head"><h2>Activity</h2></div>
40
+ <ol class="feed" id="events"></ol>
41
+ </section>
42
+ <div class="stack">
43
+ <section class="glass">
44
+ <div class="head"><h2>When homes show up</h2><span class="muted">Amsterdam time</span></div>
45
+ <div class="heat" id="heat"></div>
46
+ </section>
47
+ <section class="glass" id="cities-box" hidden>
48
+ <div class="head"><h2>By city</h2></div>
49
+ <ul class="bars" id="cities"></ul>
50
+ </section>
51
+ <section class="glass" id="buildings-box" hidden>
52
+ <div class="head"><h2>New buildings</h2><span class="muted">new on codomo.eu</span></div>
53
+ <ul class="list compact" id="buildings"></ul>
54
+ </section>
55
+ </div>
56
+ </div>
57
+
58
+ <footer>
59
+ <span>Unofficial. Not affiliated with Codomo (formerly Holland2Stay).</span>
60
+ <a id="version" href="https://github.com/kooroshkz/codomo-alerts" target="_blank" rel="noopener"></a>
61
+ </footer>
62
+ </main>
63
+
64
+ <div class="star" id="star">
65
+ <a href="https://github.com/kooroshkz/codomo-alerts" target="_blank" rel="noopener"
66
+ aria-label="Star codomo-alerts on GitHub">
67
+ <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M8 1.6l1.95 3.95 4.36.64-3.16 3.07.75 4.34L8 11.55 4.1 13.6l.75-4.34L1.69 6.19l4.36-.64z"/></svg>
68
+ <span>Star <span class="long">on GitHub</span></span>
69
+ </a>
70
+ <button type="button" aria-label="Hide">×</button>
71
+ </div>
72
+
73
+ <script src="app.js"></script>
74
+ </body>
75
+ </html>
@@ -0,0 +1,161 @@
1
+ """`codomo-alerts init`: a few questions, then a config file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+
10
+ import apprise
11
+
12
+ from . import PROJECT_URL, catalog, messages
13
+ from .client import Client, CodomoError
14
+ from .config import NAME, ConfigError, build, load
15
+ from .notify import Notifier
16
+ from .search import fetch
17
+ from .term import ask, bad, bold, dim, ok, warn, yes
18
+
19
+ EXAMPLES = [
20
+ ("Telegram", "tgram://BOT_TOKEN/CHAT_ID"),
21
+ ("Discord", "discord://WEBHOOK_ID/WEBHOOK_TOKEN"),
22
+ ("ntfy", "ntfy://pick-a-long-secret-topic"),
23
+ ("Email", "mailtos://you:app-password@gmail.com"),
24
+ ]
25
+
26
+
27
+ def default_path() -> Path:
28
+ xdg = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
29
+ return xdg / NAME / "config.toml"
30
+
31
+
32
+ def _valid(section: str, key: str, value) -> str | None:
33
+ try:
34
+ build({section: {key: value}}, {})
35
+ except ConfigError as e:
36
+ return str(e)
37
+ return None
38
+
39
+
40
+ def _ask_list(question: str, key: str, default: str = "") -> list[str]:
41
+ while True:
42
+ answer = ask(question, default)
43
+ values = [v.strip() for v in answer.split(",") if v.strip()]
44
+ error = _valid("search", key, values)
45
+ if not error:
46
+ return values
47
+ print(bad(error))
48
+
49
+
50
+ def _ask_one(question: str, key: str) -> str:
51
+ while True:
52
+ answer = ask(question).strip().lower()
53
+ error = _valid("search", key, answer)
54
+ if not error:
55
+ return answer
56
+ print(bad(error))
57
+
58
+
59
+ def _ask_price() -> int | None:
60
+ while True:
61
+ answer = ask("Max price per month in euro, service costs included (empty for no limit):")
62
+ if not answer:
63
+ return None
64
+ clean = "".join(c for c in answer if c not in "€,. ")
65
+ error = _valid("search", "price_max", clean)
66
+ if not error:
67
+ return int(clean)
68
+ print(bad(error))
69
+
70
+
71
+ def _ask_urls() -> list[str]:
72
+ print()
73
+ print("Where should alerts go? Paste one link per line, empty line to finish.")
74
+ for name, example in EXAMPLES:
75
+ print(dim(f" {name:9} {example}"))
76
+ print(dim(" More apps: https://github.com/caronc/apprise/wiki"))
77
+ urls: list[str] = []
78
+ while True:
79
+ url = ask(">")
80
+ if not url:
81
+ return urls
82
+ if apprise.Apprise().add(url):
83
+ urls.append(url)
84
+ print(ok("Added"))
85
+ else:
86
+ print(bad("That doesn't look like a valid link, try again"))
87
+
88
+
89
+ def _toml(search: dict, urls: list[str]) -> str:
90
+ def value(v) -> str:
91
+ return json.dumps(v, ensure_ascii=False) if not isinstance(v, bool) else str(v).lower()
92
+
93
+ lines = [f"# codomo-alerts settings. All options: {PROJECT_URL}#configuration", "", "[search]"]
94
+ for key, v in search.items():
95
+ if v not in (None, [], ""):
96
+ lines.append(f"{key} = {value(v)}")
97
+ lines += ["", "[notify]", f"urls = {value(urls)}", "", "[schedule]", 'preset = "normal"', "",
98
+ "[dashboard]", "enabled = true", "port = 8080", ""]
99
+ return "\n".join(lines)
100
+
101
+
102
+ def run(path: str | None = None) -> int:
103
+ target = Path(path).expanduser() if path else default_path()
104
+ print(bold("codomo-alerts setup"))
105
+ print(dim("Press enter to skip a question.\n"))
106
+ if target.exists() and not yes(f"{target} exists. Replace it?", default=False):
107
+ print("Nothing changed.")
108
+ return 1
109
+
110
+ for code, country in catalog.MARKETS.items():
111
+ print(dim(f"{country}: " + ", ".join(c for c, m in catalog.CITIES.items() if m == code)))
112
+ cities = _ask_list("Which cities? (comma separated, empty for every city):", "cities")
113
+ countries: list[str] = []
114
+ if not cities:
115
+ countries = _ask_list(f"Which countries? {', '.join(catalog.MARKETS.values())} (empty for all):",
116
+ "countries")
117
+ markets = build({"search": {"cities": cities, "countries": countries}}, {}).search.markets()
118
+ gender = ""
119
+ if any(m != "nl" for m in markets):
120
+ print(dim("Some rooms in Spain and Austria are for women only or for men only."))
121
+ gender = _ask_one("Only show rooms open to: female, male (empty for all):", "gender")
122
+ bedrooms = _ask_list("Bedrooms? studio, 1, 2, 3, 4 or 2+ (empty for any):", "bedrooms")
123
+ price_max = _ask_price()
124
+ contract = ask("Contract? long, short or any:", "any").strip().lower()
125
+ while contract not in ("long", "short", "any"):
126
+ contract = ask("Please type long, short or any:", "any").strip().lower()
127
+ interest = yes("Also tell you about register-interest homes (Codomo picks from a shortlist)?", default=True)
128
+ urls = _ask_urls()
129
+
130
+ search = {"countries": countries, "cities": cities, "bedrooms": bedrooms, "price_max": price_max,
131
+ "contract": [] if contract == "any" else [contract], "gender": gender, "interest": interest}
132
+ target.parent.mkdir(parents=True, exist_ok=True)
133
+ # notification links are secrets: private from the first byte
134
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
135
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
136
+ f.write(_toml(search, urls))
137
+ with contextlib.suppress(OSError):
138
+ os.chmod(target, 0o600) # the file may have existed with wider permissions
139
+ print()
140
+ print(ok(f"Saved {target}"))
141
+
142
+ cfg = load(str(target))
143
+ print(dim(cfg.search.summary()))
144
+ try:
145
+ found = fetch(Client(cfg.base_url), cfg.search, "available")
146
+ print(ok(f"{len(found)} home{'s' if len(found) != 1 else ''} match right now"))
147
+ for x in sorted(found.values(), key=lambda x: x.price or 0)[:5]:
148
+ print(dim(f" {messages.money(x.price):>7} {x.name}"))
149
+ except CodomoError as e:
150
+ print(warn(f"Couldn't check Codomo right now: {e}"))
151
+
152
+ if urls and yes("Send a test message?", default=True):
153
+ for url, sent in Notifier(urls).test(*messages.test()):
154
+ print(ok(url) if sent else bad(f"{url} (failed)"))
155
+ elif not urls:
156
+ print(warn("No notification links: alerts will only show in the log and the dashboard"))
157
+
158
+ flag = "" if target == default_path() else f" --config {target}"
159
+ print()
160
+ print(f"Start watching: {bold('codomo-alerts' + flag + ' watch')}")
161
+ return 0