Repository navigation
Expand file tree
/
Copy pathfetch.py
More file actions
1579 lines (1434 loc) · 69.1 KB
/
Copy pathfetch.py
File metadata and controls
1579 lines (1434 loc) · 69.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Kidsnote fetch script.
Pulls a child's reports + attached photos from Kidsnote's unofficial
/api/v1_2 endpoints, using the sessionid cookie from a logged-in browser
session, and either mirrors them straight to a Notion database
(`--publish-to-notion`) or writes them to a local folder layout for
further processing.
Local output layout (one folder per report):
<backup-root>/
20260504_093015/
note.txt
image_001.jpg
image_002.jpg
20260505_142030/
...
The endpoint paths, field names, and response shape are best-effort and
may need tweaking against your actual API responses. Run with --dump-raw
once to inspect what Kidsnote returns for your account, then adjust the
constants below if any field name has drifted.
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import re
import sys
import time
from datetime import datetime
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
import requests
from secret_input import child_label, clean_secret, mask_name, masked_value, match_children # local module
from secret_input import safe_err as _safe_err, safe_url as _safe_url # local module
try:
import browser_cookie3
except ImportError: # surface a clear hint before the first call
browser_cookie3 = None # type: ignore[assignment]
# ---------------------------------------------------------------------------
# Kidsnote endpoints (unofficial)
# ---------------------------------------------------------------------------
KIDSNOTE_BASE = "https://www.kidsnote.com"
API = f"{KIDSNOTE_BASE}/api/v1_2"
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0 Safari/537.36"
)
# Common candidate keys for the image URL inside a report's attachment object.
# Kidsnote has used "original" historically; the others are fallbacks in case
# the API has evolved.
IMAGE_URL_KEYS = ("original", "url", "src", "high", "high_resize", "large_resize")
ATTACH_LIST_KEYS = ("attached_images", "attached_pictures", "pictures", "images")
TEXT_KEYS = ("content", "body", "report")
# Video attachments — usually a single object (or None) on each report.
# Confirmed schema (2026-05-13): same shape as image attachments —
# `original` is the full-resolution URL.
VIDEO_OBJECT_KEYS = ("attached_video", "video", "attached_videos")
# Misc file attachments (PDFs, Excel etc.) — list of objects keyed by
# `original` (download URL) + `original_file_name` (display name).
FILE_LIST_KEYS = ("attached_files", "files", "attachments")
_LOGGER = logging.getLogger("kidsnote_fetch")
# ------------------------------------------------------------------
# Time budget for cron auto-resume
# ------------------------------------------------------------------
# GitHub-hosted runners hard-cap a single job at 6 hours. To make the
# multi-run backfill fully autonomous (no manual re-trigger needed)
# the workflow uses a 4-hour cron schedule and the script gracefully
# stops processing once we approach the cap. Concurrency group ensures
# the next cron run queues until the current one releases, so dedup
# picks up where we left off.
_START_TIME = time.monotonic()
# 2026-05-23: budget reshape after a single job dragged to 8h46m
# (publish loop stopped cleanly at 5h28m but dashboards ate the next
# 3h+, breaking concurrency for subsequent cron runs).
# * Publish phase budget shrunk to 4h45m (was 5h30m): leaves enough
# wall-time for dashboards within the 6h GHA hard cap.
# * Dashboard reserve raised to 30min (was 2min): publish loop now
# stops with 30 min runway so dashboards have a real chance to
# run instead of all skipping with the smaller reserve.
# Net effect: max wall-time is ~5h15m + cleanup, safely under the 6h
# GHA cap. Cron auto-resume picks up next cycle.
TIME_BUDGET_SEC = 4 * 3600 + 45 * 60 # 4h45m for alimnota publish loop
DASHBOARD_RESERVE_SEC = 30 * 60 # 30 min reserved for dashboards
def _remaining_budget() -> float:
"""Seconds remaining in the workflow's self-imposed time budget."""
return TIME_BUDGET_SEC - (time.monotonic() - _START_TIME)
def _load_env_file(path: Path) -> dict[str, str]:
"""Tiny .env parser — no python-dotenv dep, no shell expansion."""
out: dict[str, str] = {}
if not path.exists():
return out
for line in path.read_text(encoding="utf-8").splitlines():
s = line.strip()
if not s or s.startswith("#") or "=" not in s:
continue
k, _, v = s.partition("=")
v = v.strip()
# Strip surrounding quotes if user wrapped value.
if len(v) >= 2 and v[0] == v[-1] and v[0] in ('"', "'"):
v = v[1:-1]
out[k.strip()] = v
return out
def _baseline_session() -> requests.Session:
sess = requests.Session()
sess.headers.update({
"User-Agent": USER_AGENT,
"Accept": "application/json, text/plain, */*",
"Accept-Language": "ko",
"Referer": KIDSNOTE_BASE,
})
return sess
def _load_session_from_browser(browser: str) -> requests.Session:
if browser_cookie3 is None:
raise RuntimeError("Missing dependency: pip install browser-cookie3")
loaders = {
"chrome": browser_cookie3.chrome,
"firefox": browser_cookie3.firefox,
"edge": browser_cookie3.edge,
"auto": browser_cookie3.load,
}
if browser not in loaders:
raise ValueError(f"Unknown browser: {browser}")
jar = loaders[browser](domain_name="kidsnote.com")
sess = _baseline_session()
sess.cookies = jar
return sess
def _list_children(sess: requests.Session) -> list[dict[str, Any]]:
"""Look up the children registered under the logged-in account.
Confirmed against the live API on 2026-05-13: `/api/v1/me/children/`
returns a DRF-style page (`{count, next, previous, results}`), each
result is `{id, name, date_birth, gender, enrollment, family_type,
parent, created}`. We only consume `id` (and surface `name` in logs
so a multi-child household can tell which one we hit).
"""
url = f"{KIDSNOTE_BASE}/api/v1/me/children/"
r = sess.get(url, timeout=30)
if r.status_code == 401:
raise RuntimeError(
"401 on /api/v1/me/children/ - session not logged in. "
"Retry with valid credentials in .env."
)
r.raise_for_status()
data = r.json()
return data.get("results") or data.get("children") or []
def _list_reports(
sess: requests.Session, child_id: int, page_size: int = 9999
) -> list[dict[str, Any]]:
r = sess.get(
f"{API}/children/{child_id}/reports/",
params={"page_size": page_size, "tz": "Asia/Seoul", "child": child_id},
timeout=60,
)
r.raise_for_status()
body = r.json()
return body.get("results") or body.get("reports") or []
def _list_comments(
sess: requests.Session, kind: str, item_id: int
) -> list[dict[str, Any]]:
"""Comments for a report / notice / album.
Confirmed live on 2026-05-13:
GET /api/v1/reports/<id>/comments/
GET /api/v1/notices/<id>/comments/
GET /api/v1/albums/<id>/comments/ (assumed, same pattern)
`kind` is the URL segment: ``reports`` / ``notices`` / ``albums``.
Returns empty list on any error so the caller doesn't have to special-case.
"""
try:
r = sess.get(
f"{KIDSNOTE_BASE}/api/v1/{kind}/{item_id}/comments/",
timeout=15,
)
if r.status_code != 200:
return []
return r.json().get("results") or []
except Exception:
return []
def _fetch_report_detail(
sess: requests.Session, report_id: int
) -> dict[str, Any] | None:
"""Single-report endpoint returns ~15 extra `life record` fields
(meal/sleep/bowel/temperature/mood/etc) that the list endpoint omits.
Confirmed live: ``GET /api/v1_2/reports/<id>/``. Returns ``None`` on error
so the caller can fall back to the summary record from the list call.
"""
try:
r = sess.get(f"{API}/reports/{report_id}/", timeout=30)
r.raise_for_status()
return r.json()
except Exception as e:
_LOGGER.warning("report detail fetch failed for id=%d: %s", report_id, e)
return None
def _list_menus(
sess: requests.Session, center_id: int, page_size: int = 9999
) -> list[dict[str, Any]]:
"""Daily lunch menu for a daycare center. Confirmed live on 2026-05-13:
GET /api/v1/centers/<center_id>/menu/?page_size=9999
Each result: {id, date_menu, morning, morning_snack, lunch,
afternoon_snack, dinner} + per-item *_img attachments
(Kakao-CDN photos of the served food). `date_menu` is ISO date.
"""
url = f"{KIDSNOTE_BASE}/api/v1/centers/{center_id}/menu/"
r = sess.get(url, params={"page_size": page_size}, timeout=60)
r.raise_for_status()
body = r.json()
return body.get("results") or []
def _list_paginated(
sess: requests.Session, url: str, page_size: int = 100, max_pages: int = 30
) -> list[dict[str, Any]]:
"""Walk a cursor-paginated DRF endpoint until exhausted.
Defensive against:
- Cursor cycles (kidsnote occasionally returns a cursor that loops back to
data it already gave us → infinite pagination with duplicate results).
- Buggy ``next`` tokens that never become None.
Stops when (a) ``next`` is None, (b) we've already seen the cursor, or
(c) we hit ``max_pages``. Duplicate ids inside results are also
deduped on output.
"""
out: list[dict[str, Any]] = []
seen_ids: set[Any] = set()
seen_cursors: set[str] = set()
next_url: str | None = url
pages = 0
while next_url and pages < max_pages:
sep = "&" if "?" in next_url else "?"
if "page_size=" not in next_url:
next_url = f"{next_url}{sep}page_size={page_size}"
r = sess.get(next_url, timeout=60)
r.raise_for_status()
body = r.json()
results = body.get("results") or []
# Dedup by id (kidsnote cursor sometimes returns overlap)
new_in_page = 0
for item in results:
iid = item.get("id")
if iid is not None and iid in seen_ids:
continue
if iid is not None:
seen_ids.add(iid)
out.append(item)
new_in_page += 1
nxt = body.get("next")
if not nxt:
break
if nxt in seen_cursors:
_LOGGER.info("pagination: cursor cycle detected after %d pages, stopping", pages + 1)
break
seen_cursors.add(nxt)
if new_in_page == 0:
_LOGGER.info("pagination: 0 new items in page %d, stopping", pages + 1)
break
if nxt.startswith("http"):
next_url = nxt
else:
base = url.split("?")[0]
next_url = f"{base}?page_size={page_size}&cursor={nxt}"
pages += 1
if pages >= max_pages:
_LOGGER.warning("pagination: hit max_pages=%d (%d items so far)", max_pages, len(out))
return out
def _list_notices(
sess: requests.Session, center_id: int
) -> list[dict[str, Any]]:
"""Center-wide notices (`/api/v1/centers/<id>/notices/`).
Cursor-paginated; we walk the full history. Each result has the same
shape as a report (title/content/author/attached_images/video/files).
"""
return _list_paginated(
sess, f"{KIDSNOTE_BASE}/api/v1/centers/{center_id}/notices/"
)
def _list_albums(
sess: requests.Session, child_id: int
) -> list[dict[str, Any]]:
"""Photo albums for one child (`/api/v1/children/<id>/albums/`)."""
return _list_paginated(
sess, f"{KIDSNOTE_BASE}/api/v1/children/{child_id}/albums/"
)
def _first_existing_key(d: dict[str, Any], keys: tuple[str, ...]) -> Any:
for k in keys:
if k in d:
return d[k]
return None
def _parse_report_datetime(report: dict[str, Any]) -> datetime:
"""Pick the most useful timestamp for the folder name.
Real-world Kidsnote responses (2026-05-13): `date_written` is a date-only
field (parses to midnight), while `created` / `modified` carry full
`YYYY-MM-DDTHH:MM:SS+09:00`. We want stable, content-anchored folder
names matching the existing BackupKidsnote layout, so:
1. Prefer `date_written` when it has a non-midnight time component.
2. Otherwise use `modified` / `created` (they keep HH:MM:SS so the same
report doesn't shift folders on re-fetch).
3. Fall back to date-only `date_written` if nothing better is available.
"""
def _parse(raw: Any) -> datetime | None:
if not raw:
return None
try:
return datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
except ValueError:
return None
written = _parse(report.get("date_written"))
if written is not None and (written.hour or written.minute or written.second):
return written
for k in ("modified", "created", "date_modified", "date_created"):
dt = _parse(report.get(k))
if dt is not None:
return dt
return written or datetime.now()
def _save_report(
sess: requests.Session,
report: dict[str, Any],
backup_root: Path,
) -> tuple[Path, int]:
"""Mirror BackupKidsnote-compatible layout for one report. Returns (folder, n_new_files)."""
dt = _parse_report_datetime(report)
folder = backup_root / dt.strftime("%Y%m%d_%H%M%S")
folder.mkdir(parents=True, exist_ok=True)
new_files = 0
# note.txt
text = _first_existing_key(report, TEXT_KEYS) or ""
note_path = folder / "note.txt"
if not note_path.exists():
note_path.write_text(text, encoding="utf-8")
new_files += 1
# photos
images = _first_existing_key(report, ATTACH_LIST_KEYS) or []
for i, img in enumerate(images, start=1):
if _download_attachment(
sess, img, folder, f"image_{i:03d}", default_suffix=".jpg"
):
new_files += 1
# video (single, or None)
video = None
for k in VIDEO_OBJECT_KEYS:
v = report.get(k)
if isinstance(v, dict):
video = v
break
if isinstance(v, list) and v and isinstance(v[0], dict):
video = v[0]
break
if video is not None:
if _download_attachment(
sess, video, folder, "video_001", default_suffix=".mp4"
):
new_files += 1
# generic files (PDFs, Excel, etc.)
files = _first_existing_key(report, FILE_LIST_KEYS) or []
for i, fobj in enumerate(files, start=1):
if _download_attachment(
sess, fobj, folder, f"file_{i:03d}", default_suffix=".bin",
keep_original_name=True,
):
new_files += 1
return folder, new_files
def _download_attachment(
sess: requests.Session,
obj: Any,
folder: Path,
stem: str,
*,
default_suffix: str,
keep_original_name: bool = False,
) -> bool:
"""Download one attachment (image / video / file). Returns True if a new
file landed on disk, False if skipped (no URL) or already cached.
`stem` is the base filename without suffix (e.g. ``image_001`` / ``video_001``).
`default_suffix` is used when neither the URL path nor `original_file_name`
carry a recognizable extension.
`keep_original_name` (file attachments only) makes the saved filename
``<stem>_<original_file_name>`` so a PDF/XLSX keeps its identifying name
while still sorting deterministically alongside other attachments.
"""
if isinstance(obj, str):
url = obj
orig_name = None
elif isinstance(obj, dict):
url = _first_existing_key(obj, IMAGE_URL_KEYS)
orig_name = obj.get("original_file_name")
else:
return False
if not url:
return False
# Pick a suffix: original_file_name > URL path > default.
suffix = ""
if orig_name:
suffix = Path(orig_name).suffix.lower()
if not suffix:
suffix = Path(urlparse(url).path).suffix.lower()
if not suffix:
suffix = default_suffix
name = stem + suffix
if keep_original_name and orig_name:
# Sanitise: drop any path components + suffix duplication.
safe = re.sub(r"[^\w.\- ]", "_", Path(orig_name).stem).strip() or stem
name = f"{stem}_{safe}{suffix}"
out = folder / name
if out.exists():
return False
try:
r = sess.get(url, timeout=180, stream=True)
r.raise_for_status()
with out.open("wb") as fh:
for chunk in r.iter_content(chunk_size=64 * 1024):
if chunk:
fh.write(chunk)
return True
except Exception as e:
_LOGGER.warning("attachment %s (%s) failed in %s: %s",
name, _safe_url(url), folder.name, _safe_err(e))
return False
def _live_page_ids(
page_map: dict[int, str],
publish_results: list[dict[str, Any]],
force_refresh: bool,
) -> dict[int, str]:
"""kidsnote id → Notion page id for the 📥 dashboard links.
Pages created this run win. Under --force-refresh the pre-run pages are
archived as they get replaced, so only this run's pages are safe to link.
"""
out: dict[int, str] = {} if force_refresh else dict(page_map)
for res in publish_results:
rid = res.get("report_id", res.get("item_id"))
if rid is not None and res.get("page_id"):
out[int(rid)] = res["page_id"]
return out
SUPPLIES_COMMENT_RESERVE_SEC = 5 * 60 # stop comment lookups this close to the cap
# Attached documents re-read per run for the 📋 board (newest posts first):
# enough for a month of plans / 가정통신문, small enough to stay cheap every 6h.
SUPPLIES_MAX_ATTACHMENTS = 12
def _publish_supplies(
mirror: Any,
sess: requests.Session,
reports: list[dict[str, Any]],
notices: list[dict[str, Any]],
page_ids: dict[int, str],
) -> None:
"""📋 준비물·일정 page. Never fails the run: any error is a warning.
Comment lookups (a handful per run) stop when the job is within a few
minutes of its time cap, so a slow kidsnote can't push the run over it.
"""
try:
import doc_text
import supplies
from notion_mirror import declared_size, fetch_capped, file_objects, media_name, media_url
lookups = 0
def comments_of(kind: str, item: dict[str, Any]) -> list[dict[str, Any]]:
nonlocal lookups
if _remaining_budget() < SUPPLIES_COMMENT_RESERVE_SEC:
return []
lookups += 1
return mirror._fetch_comments(sess, kind, int(item["id"]))
downloads = 0
def attachment_texts_of(item: dict[str, Any]) -> list[tuple[str, str]]:
"""Text of the readable documents attached to a teacher post."""
nonlocal downloads
out: list[tuple[str, str]] = []
for obj in file_objects(item):
name, url, size = media_name(obj, "file"), media_url(obj), declared_size(obj)
if not (url and doc_text.can_extract(name)):
continue
if size is not None and size > doc_text.MAX_INPUT_BYTES:
continue
if (downloads >= SUPPLIES_MAX_ATTACHMENTS
or _remaining_budget() < SUPPLIES_COMMENT_RESERVE_SEC):
break
downloads += 1
try:
raw = fetch_capped(sess, url, doc_text.MAX_INPUT_BYTES, 60)
except Exception as e:
_LOGGER.info("📋 attachment %s not read: %s", name, _safe_err(e))
continue
text = doc_text.extract_text(raw or b"", name)
if text:
out.append((name, text))
return out
posts = supplies.posts_from_kidsnote(reports, notices, page_ids, comments_of,
attachment_texts_of=attachment_texts_of)
board = supplies.build_board(posts)
titles = {int(n["id"]): (n.get("title") or "").strip()
for n in notices if n.get("id") is not None}
calendar_id = None
try:
calendar_id = mirror.sync_calendar(board, titles, {(p.item_id, p.source) for p in posts})
except Exception as e: # the calendar is extra: never block the 📋 page
_LOGGER.warning("calendar sync failed: %s", _safe_err(e))
mirror.publish_supplies(board, titles, calendar_id)
_LOGGER.info(
"📋 Supplies page updated (%d upcoming dates, %d requests; %d posts read, "
"%d comment lookups, %d attachments read)", len(board.events), len(board.requests),
len(posts), lookups, downloads,
)
except Exception as e:
_LOGGER.warning("supplies publish failed: %s", _safe_err(e))
def _resolve_secret(env: dict[str, str], key: str) -> str:
"""Read a credential from either the .env file or the process environment.
The GitHub Actions workflow injects secrets via os.environ, so we treat
that as authoritative if present; otherwise we fall back to the .env file
used for local runs.
"""
return os.environ.get(key, "") or env.get(key, "")
def _truthy(value: str) -> bool:
"""Parse a workflow input / env var into a bool.
GitHub Actions ``workflow_dispatch`` choice inputs arrive as strings
(``"true"`` / ``"false"``), so a naive ``bool()`` of the raw string would
treat ``"false"`` as truthy. Accepts the common forms operators type.
"""
return value.strip().lower() in ("true", "1", "yes", "on", "y")
def _chronological_key(item: dict[str, Any]) -> tuple[str, int]:
"""Sort key that puts the oldest item first.
Sort priority: ``date_written`` > ``created`` > id. Falls back to the
item's id (numeric) for stable ordering when dates collide or are
missing. Kidsnote ids are monotonic, so id-as-secondary keeps near-
chronological order even for items that share a date.
"""
date = (item.get("date_written") or item.get("created") or "")[:10]
iid = item.get("id") or 0
try:
iid = int(iid)
except (TypeError, ValueError):
iid = 0
return (date, iid)
def _pick_child(
children: list[dict[str, Any]],
child_id: int | None,
child_name: str,
child_index: int | None,
) -> dict[str, Any]:
"""Resolve which child to mirror from the multi-child profile.
Priority: explicit id > name substring match > 1-based index > children[0].
Name match is case-insensitive Korean substring (e.g. ``유주`` matches
``우유주``). Raises SystemExit with the available list if nothing matches —
that's nearly always more helpful than silently defaulting to children[0],
which was the original cause of the "I selected the second child in the
web UI but got the first child's data" bug report.
"""
if not children:
sys.exit("no children found on this account.")
if child_id is not None:
match = next((c for c in children if c.get("id") == child_id), None)
if match is None:
avail = ", ".join(f"{c.get('id')}={mask_name(c.get('name'))}" for c in children)
sys.exit(f"--child-id {child_id} not in your profile. Available: {avail}")
return match
if clean_secret(child_name):
# Same rule as preflight.py (secret_input.match_children).
outcome, matches = match_children(children, child_name)
avail = ", ".join(f"{c.get('id')}={child_label(c)}" for c in children)
if outcome == "several":
sys.exit(f"--child-name {masked_value(child_name)!r} holds more than one name; "
f"give one child per slot. Available: {avail}")
if outcome == "none":
sys.exit(f"--child-name {masked_value(child_name)!r} matched no child. Available: {avail}")
if outcome == "many":
picked = ", ".join(f"{c.get('id')}={child_label(c)}" for c in matches)
sys.exit(
f"--child-name {masked_value(child_name)!r} ambiguous ({len(matches)} matches): "
f"{picked}. Use --child-id instead for an exact pick."
)
return matches[0]
if child_index is not None:
if child_index < 1 or child_index > len(children):
sys.exit(
f"--child-index {child_index} out of range (have {len(children)} child(ren))"
)
return children[child_index - 1]
return children[0]
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(
description="Personal Kidsnote fetcher - not part of the public package."
)
ap.add_argument("--backup-root", type=Path,
help="Folder where reports + photos will land. "
"Required unless --no-local-save is set.")
ap.add_argument("--no-local-save", action="store_true",
help="Skip writing reports to disk. Use with "
"--publish-to-notion when running in a stateless "
"CI runner (GitHub Actions).")
ap.add_argument("--publish-to-notion", action="store_true",
help="Mirror each new report to a Notion database. "
"Reads NOTION_TOKEN + NOTION_DATABASE_ID from .env or "
"process env (whichever is set).")
ap.add_argument("--auth-mode", default="session-cookie-env",
choices=["session-cookie-env", "browser-cookie"],
help="session-cookie-env (default): logs in with KIDSNOTE_USERNAME / "
"KIDSNOTE_PASSWORD, falling back to KIDSNOTE_SESSION_COOKIE "
"(value of `sessionid`). Required for headless CI. "
"browser-cookie: pulls cookies from a locally logged-in browser.")
ap.add_argument("--env-file", type=Path,
default=Path(__file__).resolve().parents[2] / ".env",
help="Path to the .env that holds KIDSNOTE_SESSION_COOKIE / NOTION_TOKEN / "
"NOTION_DATABASE_ID. Ignored if the same names exist in process env (CI mode).")
ap.add_argument("--browser", default="auto",
choices=["chrome", "firefox", "edge", "auto"],
help="(--auth-mode browser-cookie only)")
# ---- Child selection (priority: id > name > index > first) ----
# Multi-child accounts: previously the script silently defaulted to the
# first child the API returned, which surprised operators who had
# "switched active child" in the kidsnote web UI (a sessionid cookie is
# not child-scoped — switching in the web changes nothing for the API).
# Three knobs now cover the realistic cases.
ap.add_argument("--child-id", type=int,
help="Pick a specific child id (exact). "
"See startup log for available ids on your account.")
ap.add_argument("--child-name", default="",
help="Pick by case-insensitive substring of child's name "
"(e.g. '유주' to match '우유주'). "
"Errors out if multiple match — use --child-id instead.")
ap.add_argument("--child-index", type=int,
help="Pick by 1-based position in the children list "
"(only useful when names collide).")
ap.add_argument("--no-menus", action="store_true",
help="Skip daily lunch menu sync.")
ap.add_argument("--no-notices", action="store_true",
help="Skip center-wide notice sync.")
ap.add_argument("--no-albums", action="store_true",
help="Skip photo album sync.")
# ---- LLM toggles -----
# The script can be split into two layers of LLM-driven content:
# 1. Per-alimnota inline callouts: 💭 요약 / 🧒 자녀의 일기 /
# 👨👩👧 부모의 편지 (3 LLM calls × every report).
# 2. Four standalone dashboard pages: 📖 매월 성장 스토리 / 🌟 마일스톤
# / 🌱 분기 관심사 / 💌 선생님께 감사 카드.
# `--no-llm` (or DISABLE_ALL_LLM=true) flips BOTH layers off in one shot,
# producing a plain backup + the 3 statistical dashboards (📊 통계 /
# 📅 추억 / 🥗 영양) that don't need LLM. Graduate-backup operators and
# privacy-conscious users typically want this. The 4 individual
# dashboard toggles are still available for fine-grained tuning when
# only some of the dashboards read awkwardly.
ap.add_argument("--no-llm", action="store_true",
help="Plain backup + statistical dashboards only. Skips ALL "
"AI-generated content: alimnota callouts (요약/자녀일기/"
"부모편지) AND the 4 LLM dashboards. Equivalent to setting "
"DISABLE_ALL_LLM=true.")
ap.add_argument("--no-growth-story", action="store_true",
help="Skip 📖 매월 성장 스토리 (LLM-written paragraph per month).")
ap.add_argument("--no-milestones", action="store_true",
help="Skip 🌟 마일스톤 (LLM-extracted '처음 ...' moments).")
ap.add_argument("--no-interests", action="store_true",
help="Skip 🌱 분기 관심사 (LLM-summarized themes per quarter).")
ap.add_argument("--no-teacher-thanks", action="store_true",
help="Skip 💌 선생님께 감사 카드 (LLM-drafted thank-you letter).")
ap.add_argument("--limit", type=int,
help="Only sync the N most recent reports (debugging).")
ap.add_argument("--monthly-sample", action="store_true",
help="For unit testing: pick one report per month (newest "
"of each calendar month), instead of N most-recent. "
"Useful to verify coverage across a wide date range.")
ap.add_argument("--force-refresh", action="store_true",
help="Re-publish every report by archiving its existing "
"Notion page first (bypasses Report-ID dedup). Use "
"after prompt/LLM changes so old callouts get "
"regenerated. Sentinel dashboard pages are never "
"touched by this — they're always replaced anyway.")
ap.add_argument("--relabel-existing", action="store_true",
help="Rewrite outdated label text (life-record chips, weather callout, "
"bowel lines) on already-published report pages in place, only where "
"it matches what an older version rendered. Pages keep their links.")
ap.add_argument("--dump-raw", action="store_true",
help="Dump the raw /reports/ JSON to backup_root for inspection. "
"Ignored when --no-local-save is set.")
ap.add_argument("--verbose", "-v", action="store_true")
args = ap.parse_args(argv)
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
# Sanity: at least one output channel must be active.
if not args.no_local_save and args.backup_root is None:
sys.exit("--backup-root is required unless --no-local-save is set.")
if args.no_local_save and not args.publish_to_notion:
sys.exit("--no-local-save is only useful with --publish-to-notion.")
env = _load_env_file(args.env_file) if args.env_file.exists() else {}
# ---- auth -----
if args.auth_mode == "session-cookie-env":
from kidsnote_auth import AuthError, resolve_session # local module
username = _resolve_secret(env, "KIDSNOTE_USERNAME")
password = _resolve_secret(env, "KIDSNOTE_PASSWORD")
cookie_val = _resolve_secret(env, "KIDSNOTE_SESSION_COOKIE")
if not (username and password) and not cookie_val:
sys.exit(
"Kidsnote credentials missing. Set KIDSNOTE_USERNAME + "
"KIDSNOTE_PASSWORD (auto-login) or KIDSNOTE_SESSION_COOKIE "
"in .env (local) or as repo secrets (GitHub Actions)."
)
# Validates the session up front, so a dead login stops here before
# any Notion work. In CI the "Kidsnote login" workflow step already
# logged in and passes the fresh sessionid via KIDSNOTE_SESSION_COOKIE.
try:
session = resolve_session(username, password, cookie_val, USER_AGENT)
except AuthError as e:
sys.exit(f"Kidsnote login failed ({e.reason}): {e}")
if session.login_error is not None:
_LOGGER.warning(
"Kidsnote id/password login failed (%s: %s); continuing with KIDSNOTE_SESSION_COOKIE",
session.login_error.reason, session.login_error,
)
sess = _baseline_session()
sess.cookies.set("sessionid", session.sessionid, domain="www.kidsnote.com", path="/")
_LOGGER.info(
"Kidsnote session ready (%s)",
"fresh login" if session.source == "login" else "KIDSNOTE_SESSION_COOKIE",
)
else:
sess = _load_session_from_browser(args.browser)
# ---- Resolve LLM master toggle once, used in two places ----
# CLI flag wins; env var (= workflow input passthrough) is the fallback.
# When the master is on, the per-alimnota callouts AND every LLM
# dashboard get short-circuited — see below.
disable_all_llm = args.no_llm or _truthy(_resolve_secret(env, "DISABLE_ALL_LLM"))
# ---- Notion mirror setup (if requested) -----
# 2026-05-25: multi-child support. Collect (token, db_id) pairs from
# numbered secrets so a 2/3/.../N-child account can back up each child
# into a separate Notion DB without operator-side child_name input.
#
# Pairing rules:
# * NOTION_DATABASE_ID (required, slot 1)
# * NOTION_DATABASE_ID_2 / _3 / ... (optional, slots 2-10)
# * NOTION_TOKEN_<N> reuses NOTION_TOKEN when not provided — most
# setups share one integration token across the workspace.
# API child[0] → slot 1, child[1] → slot 2, etc. Operators who need
# a different mapping (gender/age order vs API order) can still set
# KIDSNOTE_CHILD_NAME_<N> to override per slot.
mirror = None # legacy single-mirror reference (kept for one-child path)
skip_ids: set[int] = set()
page_map: dict[int, str] = {}
notion_slots: list[dict[str, Any]] = [] # [{db_id, token, child_name_override}]
if args.publish_to_notion:
from notion_mirror import NotionMirror # local module
token0 = _resolve_secret(env, "NOTION_TOKEN")
db_id0 = _resolve_secret(env, "NOTION_DATABASE_ID")
if not token0 or not db_id0:
sys.exit(
"NOTION_TOKEN / NOTION_DATABASE_ID missing. "
"Set them in .env (local) or as repo secrets (GitHub Actions)."
)
notion_slots.append({
"db_id": db_id0,
"token": token0,
"name_override": _resolve_secret(env, "KIDSNOTE_CHILD_NAME"),
})
# Slots 2..10 are optional. Stop scanning at the first gap.
for slot in range(2, 11):
db_n = _resolve_secret(env, f"NOTION_DATABASE_ID_{slot}")
if not db_n:
break
notion_slots.append({
"db_id": db_n,
"token": _resolve_secret(env, f"NOTION_TOKEN_{slot}") or token0,
"name_override": _resolve_secret(env, f"KIDSNOTE_CHILD_NAME_{slot}"),
})
if len(notion_slots) > 1:
_LOGGER.info(
"Multi-child mode: %d Notion DB slots detected",
len(notion_slots),
)
# For backward compatibility the original single-mirror path below
# uses the first slot. Multi-child loop wraps this same logic per
# slot further down.
mirror = NotionMirror(token=token0, database_id=db_id0)
# Master switch: propagate to the mirror so per-alimnota callouts
# (요약 / 자녀일기 / 부모편지) are skipped during publishing.
if disable_all_llm:
mirror.disable_llm_callouts = True
_LOGGER.info(
"🚫 --no-llm / DISABLE_ALL_LLM is ON — alimnota AI callouts and "
"the 4 LLM dashboards will all be skipped (plain backup + "
"statistical dashboards only)."
)
try:
page_map = mirror.existing_report_page_map()
if args.force_refresh:
_LOGGER.info(
"Notion DB: --force-refresh active, %d existing pages will be "
"archived + re-published", len(page_map),
)
# Empty skip_ids so every report gets re-published.
else:
skip_ids = set(page_map.keys())
_LOGGER.info(
"Notion DB: %d existing report pages will be skipped", len(skip_ids),
)
except Exception as e:
sys.exit(f"Notion DB query failed: {e}")
# ---- enumerate child + reports -----
children = _list_children(sess)
# ALWAYS print the full child roster so operators can self-diagnose
# multi-child accounts. Previously the only log line was "fetched N
# reports for child id=...", which silently swallowed the selection.
if children:
_LOGGER.info(
"Account has %d child(ren): %s",
len(children),
", ".join(f"#{i + 1} id={c.get('id')} name={mask_name(c.get('name'))}"
for i, c in enumerate(children)),
)
# Resolve which child to mirror. CLI flag wins over env var so a manual
# workflow run can override the repo-secret default without editing it.
child_name = args.child_name or _resolve_secret(env, "KIDSNOTE_CHILD_NAME")
target = _pick_child(children, args.child_id, child_name, args.child_index)
_LOGGER.info(
"Selected child: id=%s name=%s (override with --child-id / --child-name / KIDSNOTE_CHILD_NAME)",
target.get("id"), mask_name(target.get("name")),
)
reports = _list_reports(sess, int(target["id"]))
if args.monthly_sample:
# One report per (YYYY-MM). Reports are newest-first so the first
# seen per month is the latest of that month.
seen_months: set[str] = set()
sampled: list[dict[str, Any]] = []
for r in reports:
ym = (r.get("date_written") or "")[:7]
if ym and ym not in seen_months:
seen_months.add(ym)
sampled.append(r)
reports = sampled
_LOGGER.info("monthly-sample mode: kept %d reports (one per month)",
len(reports))
elif args.limit:
reports = reports[: args.limit]
_LOGGER.info("fetched %d reports for child id=%s",
len(reports), target.get("id"))
# Enrich reports with detail API in one pass — both the publish step and
# the dashboard stats need fields that only the detail endpoint exposes
# (meal_status / sleep_hour / weather / food / sleep / nursing / bowel).
# 1 extra HTTP call per report, but skipping it would force two passes.
if mirror is not None and reports:
_LOGGER.info("enriching %d reports with detail API...", len(reports))
enriched: list[dict[str, Any]] = []
for i, r in enumerate(reports, 1):
d = _fetch_report_detail(sess, int(r["id"])) or r
enriched.append(d)
if i % 5 == 0 or i == len(reports):
_LOGGER.info(" detail enrich %d/%d done", i, len(reports))
reports = enriched
_LOGGER.info("detail enrich complete")
# ---- --relabel-existing: fix label wording on already-published pages ----
if args.relabel_existing and mirror is not None and reports:
if args.force_refresh:
_LOGGER.info("🏷️ Relabel skipped: --force-refresh re-publishes every page anyway")
else:
from relabel import relabel_report_pages # local module
_LOGGER.info("🏷️ Relabel: checking %d published report pages...",
sum(1 for r in reports if int(r.get("id") or 0) in page_map))
relabel_counts = relabel_report_pages(
mirror, reports, page_map,
time_left=lambda: _remaining_budget() - DASHBOARD_RESERVE_SEC,
)
_LOGGER.info("🏷️ Relabel done: %s",
", ".join(f"{k}={v}" for k, v in relabel_counts.items()))
# ---- local save (optional) -----
total_new_files = 0
if not args.no_local_save:
args.backup_root.mkdir(parents=True, exist_ok=True)
if args.dump_raw:
raw_path = args.backup_root / f"_raw_reports_{target['id']}.json"
raw_path.write_text(
json.dumps(reports, ensure_ascii=False, indent=2), encoding="utf-8"
)
_LOGGER.info("dumped raw JSON to %s", raw_path)
for r in reports:
folder, n_new = _save_report(sess, r, args.backup_root)
total_new_files += n_new
if args.verbose:
_LOGGER.debug(" %s (+%d files)", folder.name, n_new)
_LOGGER.info("local save: %d reports, %d new files under %s",
len(reports), total_new_files, args.backup_root)
# Accumulator for attachment counts (across all kinds).
publish_results: list[dict[str, Any]] = []
# ---- helper: publish a batch of items via the given publish method ----
def _publish_batch(
items: list[dict[str, Any]],
publish_fn: Any,
kind_label: str,
) -> None:
# `publish_fn` is mirror.publish_notice / publish_album / publish_menu.
# Dedup against the same skip_ids set (Report ID is shared column).
to_pub = [x for x in items if int(x.get("id", 0)) not in skip_ids]
already = len(items) - len(to_pub)
total = len(to_pub)
_LOGGER.info(
"%s mirror: %d total fetched, %d already in DB (skip), %d to publish",
kind_label, len(items), already, total,
)
pub = 0
fail = 0
stopped_early = False
for idx, x in enumerate(to_pub, start=1):
# Graceful exit before the 6h hard cap so cron auto-resume
# has time to write the dashboards instead of being SIGTERM'd
# mid-page-create.
if _remaining_budget() < DASHBOARD_RESERVE_SEC:
_LOGGER.warning(
"%s mirror: time budget reached at %d/%d, stopping early. "