Coverage for src/sync.py: 100%

704 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-03 03:08 +0000

1"""Sync module.""" 

2 

3__author__ = "Mandar Patil <mandarons@pm.me>" 

4import datetime 

5import os 

6import re 

7import secrets 

8from time import sleep 

9 

10import requests 

11from icloudpy import ICloudPyService, exceptions, utils 

12 

13from src import ( 

14 CHINA_HOME_ENDPOINT, 

15 CHINA_SETUP_ENDPOINT, 

16 DEFAULT_CONFIG_FILE_PATH, 

17 DEFAULT_RETRY_LOGIN_INTERVAL_SEC, 

18 ENV_CONFIG_FILE_PATH_KEY, 

19 ENV_ICLOUD_PASSWORD_KEY, 

20 apply_default_request_timeout, 

21 config_parser, 

22 configure_icloudpy_logging, 

23 get_logger, 

24 notify, 

25 read_config, 

26 sync_drive, 

27 sync_photos, 

28) 

29from src.sync_stats import SyncSummary 

30from src.usage import alive 

31 

32# Configure icloudpy logging immediately after import 

33configure_icloudpy_logging() 

34 

35LOGGER = get_logger() 

36 

37 

38_TRUST_COOKIE_NAME = "X-APPLE-WEBAUTH-HSA-TRUST" 

39 

40 

41def _detect_security_key_account(api, username: str) -> bool: 

42 """True when Apple answers this account's second factor with an fsaChallenge. 

43 

44 Once security keys are enrolled Apple stops issuing 6-digit codes 

45 altogether, so requesting a push sends nothing and listening for a 

46 replied code waits for something that cannot arrive -- the loop did 

47 both, every cycle, and told the user over Telegram to "reply the 

48 6-digit code here". Detecting it here rather than waiting for someone 

49 to open the dashboard is what lets the very first notification tell 

50 the truth. 

51 

52 Recording the method also means ``notify`` picks the security-key 

53 wording on this same pass, since it reads the same signal. 

54 

55 Best-effort in both directions: icloudpy without security-key support 

56 has no such attribute, and no probe failure may break the retry loop. 

57 """ 

58 try: 

59 challenge = getattr(api, "security_key_challenge", None) 

60 except Exception as e: # noqa: BLE001 - a probe must never break the loop 

61 LOGGER.debug(f"security-key probe failed: {e!s}") 

62 return False 

63 # Shape, not truthiness. icloudpy returns a mapping carrying "challenge" 

64 # and "keyHandles", or None -- anything else (a stub, a changed API, a 

65 # sentinel) must not be mistaken for Apple demanding a key, because the 

66 # cost of a false positive is suppressing the real code flow. 

67 if not (isinstance(challenge, dict) and challenge.get("challenge")): 

68 return False 

69 try: 

70 from src import web_signals 

71 

72 web_signals.record_auth_method(username=username, method="security_key") 

73 except Exception as e: # noqa: BLE001 - wording is not worth an outage 

74 LOGGER.debug(f"could not record auth method: {e!s}") 

75 return True 

76 

77 

78def _log_trust_revocation_hint(api) -> None: 

79 """Say so when Apple rejected a trust token that has not expired. 

80 

81 Expiry and revocation are indistinguishable from the logs -- both 

82 surface as 421 and both end with a 2FA prompt -- but they mean 

83 opposite things for what to do next. A refresh schedule prevents the 

84 first and can do nothing about the second: Apple drops trust on 

85 security events, typically a new trusted device, a password change, 

86 or a change to security keys. 

87 

88 Without this, the obvious reading of "valid trust token, 2FA demanded 

89 anyway" is that the refresh logic is broken, and the time goes into 

90 auditing code that behaved correctly. 

91 

92 Best-effort: never raises into the retry path. 

93 """ 

94 try: 

95 expires_at = _read_trust_cookie_expiry(api) 

96 if expires_at is None: 

97 return 

98 remaining = ( 

99 expires_at - datetime.datetime.now(tz=datetime.UTC) 

100 ).days 

101 if remaining <= 0: 

102 return 

103 LOGGER.error( 

104 f"The trust token had not expired -- it is valid for {remaining} " 

105 f"more days (until {expires_at.date()}). Apple revoked it " 

106 f"server-side, which typically follows a new trusted device, a " 

107 f"password change, or a change to security keys.", 

108 ) 

109 except Exception as e: # noqa: BLE001 - diagnostics never break the retry 

110 LOGGER.debug(f"trust revocation hint failed: {e!s}") 

111 

112 

113def _read_trust_cookie_expiry(api) -> datetime.datetime | None: 

114 """Return the expiry datetime of Apple's HSA trust cookie, or None. 

115 

116 The trust window is carried by ``X-APPLE-WEBAUTH-HSA-TRUST`` in 

117 icloudpy's cookie jar (persisted to ``session_data/<username>`` as 

118 LWPCookieJar). Reading it directly avoids hardcoding Apple's trust 

119 duration -- the cookie's own ``expires`` field is the source of 

120 truth, set per-cookie by Apple's server. Returns None if the cookie 

121 isn't present (e.g. account never auth'd with 2FA, or trust cookie 

122 cleared). 

123 """ 

124 try: 

125 cookies = api.session.cookies 

126 except AttributeError: 

127 return None 

128 for cookie in cookies: 

129 if cookie.name == _TRUST_COOKIE_NAME and cookie.expires: 

130 return datetime.datetime.fromtimestamp( 

131 cookie.expires, 

132 tz=datetime.UTC, 

133 ) 

134 return None 

135 

136 

137# Set once the missing-public_url guidance has been logged (see 

138# ``_resolve_dashboard_url``) so the advice appears once per process, 

139# not once per sync-loop iteration. 

140_WEB_UI_PUBLIC_URL_WARNED = False 

141 

142# Minimum wait after a failed sign-in. Apple answers a throttled account 

143# with 409 on /signin/init; retrying sooner just extends the lockout. 

144_AUTH_BACKOFF_FLOOR_SEC = 1800 

145 

146 

147def _resolve_dashboard_url(config) -> str | None: 

148 """Compute the web UI URL to embed in notifications, or None. 

149 

150 Returns ``None`` when ``app.web_ui.enabled`` is False -- callers 

151 fall back to the legacy docker-exec instruction. Otherwise prefers 

152 the explicit ``app.web_ui.public_url`` (e.g. the reverse-proxy 

153 URL); falls back to ``http://{host}:{port}`` with a warning logged 

154 once at startup if the public URL isn't set. 

155 """ 

156 if not config_parser.get_web_ui_enabled(config=config): 

157 return None 

158 public_url = config_parser.get_web_ui_public_url(config=config) 

159 if public_url: 

160 return public_url 

161 host = config_parser.get_web_ui_host(config=config) 

162 port = config_parser.get_web_ui_port(config=config) 

163 # Latch: this resolves on every sync-loop iteration, and while the 

164 # container sits 2FA-pending (default 600s retry) that is ~144x/day 

165 # of identical guidance in the exact scenario the user is watching 

166 # the logs. The advice only needs saying once per process. 

167 global _WEB_UI_PUBLIC_URL_WARNED 

168 if not _WEB_UI_PUBLIC_URL_WARNED: 

169 LOGGER.warning( 

170 "app.web_ui.public_url not set -- notification URLs will use " 

171 "http://%s:%s/, which won't work from outside the container. " 

172 "Set app.web_ui.public_url to your reverse-proxy URL.", 

173 host, 

174 port, 

175 ) 

176 _WEB_UI_PUBLIC_URL_WARNED = True 

177 return f"http://{host}:{port}" 

178 

179 

180def _publish_auth_blocked(blocked: bool, reason: str | None = None) -> None: 

181 """Tell the web UI whether the loop can authenticate. 

182 

183 Only this loop knows: every on-disk signal the dashboard can check by 

184 itself (username configured, password in the keyring) still looks 

185 healthy while an account sits stuck on a second factor. 

186 

187 Best-effort -- signalling must never break syncing. 

188 """ 

189 try: 

190 from src import web_signals 

191 

192 web_signals.record_auth_blocked(blocked=blocked, reason=reason) 

193 except Exception as e: # pragma: no cover - signalling is advisory 

194 LOGGER.warning(f"Could not publish auth state: {e!s}") 

195 

196 

197def _publish_running(service: str, running: bool) -> None: 

198 """Tell the web UI a service pass started or ended. Best-effort.""" 

199 try: 

200 from src import web_signals 

201 

202 web_signals.record_service_running(service, running=running) 

203 except Exception as e: # pragma: no cover - signalling is advisory 

204 LOGGER.warning(f"Could not publish {service} sync state: {e!s}") 

205 

206 

207def _maybe_refresh_trust(config, api) -> None: 

208 """Re-trust the session before its token ages out. 

209 

210 ``trust_session`` asks Apple for a new ``X-Apple-TwoSV-Trust-Token`` 

211 and icloudpy persists it to ``session_data``. Calling it while the 

212 session is still healthy therefore rolls the window forward, so a 

213 restart at any later point finds a young token and resumes without 

214 prompting for a second factor. 

215 

216 This matters most for accounts where the second factor is expensive 

217 or impossible to satisfy headlessly (hardware security keys, where 

218 Apple refuses to send a 6-digit code at all). 

219 

220 Best-effort: never raises into the sync loop. 

221 """ 

222 try: 

223 threshold = config_parser.get_trust_refresh_days(config=config) 

224 if threshold <= 0: 

225 return 

226 expires_at = _read_trust_cookie_expiry(api) 

227 if expires_at is None: 

228 return 

229 days_remaining = ( 

230 expires_at - datetime.datetime.now(tz=datetime.UTC) 

231 ).days 

232 if days_remaining > threshold: 

233 return 

234 LOGGER.info( 

235 f"Trust token has {days_remaining}d left (threshold {threshold}d) -- refreshing.", 

236 ) 

237 if api.trust_session(): 

238 refreshed = _read_trust_cookie_expiry(api) 

239 expires_at_iso = refreshed.isoformat() if refreshed else None 

240 LOGGER.info( 

241 f"Trust refreshed; now expires {expires_at_iso or 'unknown'}.", 

242 ) 

243 # Webhook-only: no other transport reports a refresh, and a 

244 # receiver tracking the trust window needs the new expiry as 

245 # much as it needs the warning that preceded it. 

246 refresh_data = {"days_remaining_before": days_remaining} 

247 if expires_at_iso: 

248 # Omitted rather than null when the cookie is unreadable. 

249 refresh_data["expires_at"] = expires_at_iso 

250 notify.post_event_to_webhook( 

251 config, 

252 "trust_refreshed", 

253 f"iCloud trust token refreshed; now expires {expires_at_iso or 'unknown'}", 

254 refresh_data, 

255 ) 

256 else: 

257 LOGGER.warning( 

258 "Proactive trust refresh was declined by Apple -- a second " 

259 "factor will be needed at the next cold start.", 

260 ) 

261 except Exception as e: # pragma: no cover - never break sync over a refresh 

262 LOGGER.warning(f"trust refresh failed: {e!s}") 

263 

264 

265def _maybe_warn_trust_expiring(config, api, username: str) -> None: 

266 """Fire the trust-expiring notification once when crossing threshold. 

267 

268 Reads the live trust cookie expiry, compares against 

269 ``app.trust_expiry_warn_days``, and -- if days_remaining is below 

270 the threshold AND we haven't already warned for THIS cookie value -- 

271 fans the warning out through ``notify.send_trust_expiring``. 

272 

273 Debounce key is the cookie expiry ISO string itself. When Apple 

274 refreshes the trust cookie (new expires_at), the stored 

275 ``warned_for_expires_at`` no longer matches and warning eligibility 

276 rearms automatically -- no manual reset needed. 

277 

278 Best-effort: any exception is logged and swallowed so a notification 

279 bug never breaks the sync loop. 

280 """ 

281 try: 

282 from src import notify, web_signals 

283 

284 expires_at = _read_trust_cookie_expiry(api) 

285 expires_at_iso = expires_at.isoformat() if expires_at else None 

286 prior = web_signals.get_trust_state() 

287 web_signals.record_trust_state( 

288 expires_at_iso=expires_at_iso, 

289 warned_for_expires_at=prior.get("warned_for_expires_at"), 

290 ) 

291 if expires_at is None: 

292 return 

293 days_remaining = ( 

294 expires_at - datetime.datetime.now(tz=datetime.UTC) 

295 ).days 

296 threshold = config_parser.get_trust_expiry_warn_days(config=config) 

297 if days_remaining >= threshold: 

298 return 

299 if prior.get("warned_for_expires_at") == expires_at_iso: 

300 return # already warned for this cookie value 

301 notify.send_trust_expiring( 

302 config=config, 

303 username=username, 

304 days_remaining=days_remaining, 

305 dashboard_url=_resolve_dashboard_url(config), 

306 ) 

307 web_signals.record_trust_state( 

308 expires_at_iso=expires_at_iso, 

309 warned_for_expires_at=expires_at_iso, 

310 ) 

311 except Exception as e: # pragma: no cover - guarded so notify bugs don't break sync 

312 LOGGER.warning(f"trust-expiring check failed: {e!s}") 

313 

314 

315_SESSION_ONLY_HELP = ( 

316 "Store an Apple ID password to let the container re-authenticate on its " 

317 "own, or create a new session by signing in from the web dashboard or " 

318 "with the documented `icloud --username=... --session-directory=...` " 

319 "command." 

320) 

321 

322# Apple answers a session it will no longer accept with one of these, and 

323# icloudpy surfaces the status as the exception's ``code``. Anything else -- 

324# a 500, a 503, a bad gateway -- is an outage that says nothing about the 

325# session, so it belongs to the loop's transport handler rather than being 

326# reported to the user as "sign in again". (icloudpy itself lumps 500 in 

327# with the re-auth statuses when it rewrites the reason; that conflation 

328# must not reach the user as an instruction.) 

329_SESSION_REJECTED_CODES = frozenset({401, 421, 450}) 

330 

331# icloudpy reads the keyring for a ``None`` password -- the very lookup 

332# session-only mode exists to avoid -- and, given ``""``, its log filter 

333# rewrites every log line with asterisks between each character. A random 

334# placeholder avoids both; ``SessionOnlyICloudPyService`` never sends it. 

335_SESSION_ONLY_PLACEHOLDER_PASSWORD = secrets.token_urlsafe(32) 

336 

337 

338class SessionOnlyICloudPyService(ICloudPyService): 

339 """An iCloud client allowed to resume a saved session and nothing else. 

340 

341 icloudpy's ``authenticate()`` tries the saved session token first and 

342 falls back to a full SRP sign-in when it does not validate. With no 

343 password that fallback cannot succeed, and letting it run would post a 

344 placeholder credential to Apple's sign-in endpoint on every retry -- 

345 the fastest way to get an Apple ID throttled or locked. So this 

346 override stops after the session check and reports the missing 

347 password instead, which the loop's existing handler already turns into 

348 a notification and a backoff. 

349 """ 

350 

351 def authenticate(self, force_refresh=False, service=None): 

352 """Validate the saved session; never sign in with credentials. 

353 

354 Raises ``ICloudPyNoStoredPasswordAvailableException`` when the 

355 session is missing or Apple has rejected it; any other API error 

356 propagates untouched, since an outage is not an expired session. 

357 

358 ``force_refresh`` is refused as defence in depth rather than 

359 because anything here asks for it: icloudpy's only caller is its 

360 Find My 450 handler, which this app never reaches. Honouring it 

361 would mean a credential sign-in, which is the one thing this class 

362 exists to prevent, so it is refused wherever it came from. 

363 """ 

364 if force_refresh or not self.session_data.get("session_token"): 

365 msg = f"No Apple ID password is stored and there is no saved session to resume. {_SESSION_ONLY_HELP}" 

366 raise exceptions.ICloudPyNoStoredPasswordAvailableException(msg) 

367 

368 try: 

369 self.data = self._validate_token() 

370 except exceptions.ICloudPyAPIResponseException as error: 

371 if error.code not in _SESSION_REJECTED_CODES: 

372 # An outage leaves the session perfectly good; reporting it as 

373 # expired would send the user off to re-authenticate for 

374 # nothing. Let the loop's transport handler have it. 

375 raise 

376 msg = f"No Apple ID password is stored and the saved session is no longer valid. {_SESSION_ONLY_HELP}" 

377 raise exceptions.ICloudPyNoStoredPasswordAvailableException(msg) from error 

378 

379 if "webservices" not in self.data: 

380 # icloudpy returns the response untouched when a failed /validate 

381 # carries no recognised error field, so ``self.data`` can be an 

382 # error body. Upstream would raise KeyError here and kill the 

383 # process -- with `restart: unless-stopped` that is a restart loop 

384 # hitting Apple on every boot. 

385 msg = f"No Apple ID password is stored and Apple did not accept the saved session. {_SESSION_ONLY_HELP}" 

386 raise exceptions.ICloudPyNoStoredPasswordAvailableException(msg) 

387 

388 self._webservices = self.data["webservices"] 

389 LOGGER.debug("Resumed the saved session without a password") 

390 

391 

392def get_api_instance( 

393 username: str, 

394 password: str | None, 

395 cookie_directory: str | None = None, 

396 server_region: str = "global", 

397) -> ICloudPyService: 

398 """ 

399 Create and return an iCloud API client instance. 

400 

401 Args: 

402 username: iCloud username/Apple ID 

403 password: iCloud password, or ``None`` to run in session-only 

404 mode -- the client then resumes the saved session in 

405 ``cookie_directory`` and refuses to sign in with credentials 

406 (see ``SessionOnlyICloudPyService``). 

407 cookie_directory: Directory to store authentication cookies. 

408 When ``None`` (the default), resolved late from 

409 ``src.DEFAULT_COOKIE_DIRECTORY`` so test fixtures that 

410 redirect the constant at runtime take effect — the previous 

411 ``= DEFAULT_COOKIE_DIRECTORY`` default-arg capture made the 

412 constant unmockable post-import. 

413 server_region: Server region ("china" or "global") 

414 

415 Returns: 

416 Configured ICloudPyService instance 

417 """ 

418 if cookie_directory is None: 

419 # Read through the src module so monkey-patches of 

420 # ``src.DEFAULT_COOKIE_DIRECTORY`` (e.g. by tests/conftest.py) 

421 # are honoured. ``src`` is this function's parent package and 

422 # already imported; using ``sys.modules`` avoids a per-call 

423 # ``import src`` and makes the data flow explicit. 

424 import sys 

425 

426 cookie_directory = sys.modules["src"].DEFAULT_COOKIE_DIRECTORY 

427 service_class = ICloudPyService 

428 if password is None: 

429 service_class = SessionOnlyICloudPyService 

430 password = _SESSION_ONLY_PLACEHOLDER_PASSWORD 

431 # Apple can report a photo library as still indexing for weeks while 

432 # listing it in full. Open it anyway: sync_photos downloads what it lists 

433 # and keeps it out of obsolete-file cleanup until the index finishes. 

434 # State the shared arguments once and add the China endpoints only for 

435 # China accounts, so the two branches cannot drift apart. 

436 api_kwargs = { 

437 "apple_id": username, 

438 "password": password, 

439 "cookie_directory": cookie_directory, 

440 "photos_require_finished_index": False, 

441 } 

442 if server_region == "china": 

443 api_kwargs["home_endpoint"] = CHINA_HOME_ENDPOINT 

444 api_kwargs["setup_endpoint"] = CHINA_SETUP_ENDPOINT 

445 api = service_class(**api_kwargs) 

446 # icloudpy's CloudKit listing calls pass no timeout and ``requests`` 

447 # has no default, so a dropped connection hangs the sync forever. 

448 # Bound the shared session for enumeration and transfers. Sign-in has 

449 # already happened inside the constructor, and the web UI's direct 

450 # ICloudPyService calls never reach here, so auth stays unbounded. 

451 apply_default_request_timeout(api.session) 

452 return api 

453 

454 

455class SyncState: 

456 """ 

457 Maintains synchronization state for drive and photos. 

458 

459 This class encapsulates the countdown timers and sync flags to avoid 

460 passing multiple variables between functions. 

461 """ 

462 

463 def __init__(self): 

464 """Initialize sync state with default values.""" 

465 self.drive_time_remaining = 0 

466 self.photos_time_remaining = 0 

467 self.enable_sync_drive = True 

468 self.enable_sync_photos = True 

469 self.last_send = None 

470 # Whether a 2FA push has already been requested for the current 

471 # re-auth episode. Reset to False on each successful authentication so 

472 # a fresh episode triggers exactly one push (see _handle_2fa_required). 

473 self.two_fa_triggered = False 

474 # Whether this cycle is running without a stored password, i.e. off 

475 # the saved session alone. Set by _authenticate_and_get_api; the error 

476 # handlers need it because nothing in that mode can be fixed by 

477 # retrying with a password the container does not have. 

478 self.session_only = False 

479 

480 

481def _load_configuration(): 

482 """ 

483 Load configuration from file or environment. 

484 

485 Returns: 

486 Configuration dictionary 

487 """ 

488 config_path = os.environ.get(ENV_CONFIG_FILE_PATH_KEY, DEFAULT_CONFIG_FILE_PATH) 

489 return read_config(config_path=config_path) 

490 

491 

492def _extract_sync_intervals(config, log_messages: bool = False): 

493 """ 

494 Extract drive and photos sync intervals from configuration. 

495 

496 Args: 

497 config: Configuration dictionary 

498 log_messages: Whether to log informational messages (default: False for loop usage) 

499 

500 Returns: 

501 tuple: (drive_sync_interval, photos_sync_interval) 

502 """ 

503 drive_sync_interval = 0 

504 photos_sync_interval = 0 

505 

506 if config and "drive" in config: 

507 drive_sync_interval = config_parser.get_drive_sync_interval( 

508 config=config, 

509 log_messages=log_messages, 

510 ) 

511 if config and "photos" in config: 

512 photos_sync_interval = config_parser.get_photos_sync_interval( 

513 config=config, 

514 log_messages=log_messages, 

515 ) 

516 

517 return drive_sync_interval, photos_sync_interval 

518 

519 

520def _retrieve_password(username: str): 

521 """ 

522 Retrieve password from environment or keyring. 

523 

524 Args: 

525 username: iCloud username 

526 

527 Returns: 

528 Password string or None if not found 

529 

530 Raises: 

531 ICloudPyNoStoredPasswordAvailableException: If password not available 

532 """ 

533 # A blank value counts as no password. Compose substitutes "" for an 

534 # unset ${VAR}, and storing it would also overwrite a real keyring 

535 # entry; returning it would skip session-only mode and send an empty 

536 # password to Apple's sign-in on every retry. 

537 password = os.environ.get(ENV_ICLOUD_PASSWORD_KEY) 

538 if password: 

539 utils.store_password_in_keyring(username=username, password=password) 

540 return password 

541 password = utils.get_password_from_keyring(username=username) 

542 if not password: 

543 msg = f"The stored password for {username} is empty." 

544 raise exceptions.ICloudPyNoStoredPasswordAvailableException(msg) 

545 return password 

546 

547 

548def _authenticate_and_get_api(config, username: str, sync_state: SyncState | None = None): 

549 """ 

550 Authenticate user and return iCloud API instance. 

551 

552 Args: 

553 config: Configuration dictionary 

554 username: iCloud username 

555 sync_state: Current sync state, whose ``session_only`` flag is set 

556 here so the error handlers can tell the two modes apart 

557 

558 Returns: 

559 ICloudPyService instance 

560 

561 Raises: 

562 ICloudPyNoStoredPasswordAvailableException: If no password is 

563 configured *and* the saved session cannot be resumed. 

564 """ 

565 server_region = config_parser.get_region(config=config) 

566 try: 

567 password = _retrieve_password(username) 

568 except exceptions.ICloudPyNoStoredPasswordAvailableException: 

569 # No password anywhere is a choice, not necessarily a misconfiguration: 

570 # an operator who would rather not keep an Apple ID password on disk 

571 # can run unattended off the saved session alone until Apple's trust 

572 # window closes. Resuming it is worth attempting before declaring 

573 # failure -- the loop used to report "password is not stored" without 

574 # ever looking at a perfectly valid session. 

575 LOGGER.debug( 

576 "No Apple ID password is configured -- resuming the saved session.", 

577 ) 

578 password = None 

579 if sync_state is not None: 

580 # Set before the client is built, so it is already right if building 

581 # it is what fails. 

582 sync_state.session_only = password is None 

583 return get_api_instance( 

584 username=username, 

585 password=password, 

586 server_region=server_region, 

587 ) 

588 

589 

590def _check_mount_marker( 

591 destinations: list[str], 

592 marker_filename: str, 

593 required: bool, 

594 service_name: str, 

595) -> bool: 

596 """Verify the failsafe marker file is present in every write destination. 

597 

598 Mirrors boredazfcuk/docker-icloudpd's ``.mounted`` pattern: protects 

599 against silent bind-mount failures (typo in the host path, missing 

600 share, wrong permissions) that would otherwise dump iCloud data into 

601 an empty container-internal directory. 

602 

603 Takes a list of destinations because a single sync may write to more 

604 than one bind-mounted directory; the marker is required in EACH write 

605 destination because any one of them could be the failed mount. 

606 

607 Returns True when it is safe to proceed (marker not required, or 

608 marker required and present in every destination). Returns False when 

609 the marker is required and is missing from at least one destination — 

610 in which case the caller should skip this sync cycle without 

611 advancing the countdown so the next interval re-checks. Every 

612 missing-marker failure is logged so the user can fix all of them in 

613 one pass rather than discovering them one cycle at a time. 

614 

615 Args: 

616 destinations: List of sync destination directories to check. Each 

617 directory is checked independently. An empty list returns 

618 True (nothing to check). 

619 marker_filename: Filename to look for inside each destination 

620 (e.g. ``.mounted``). 

621 required: Whether the marker is required at all. When False this 

622 is a no-op that always returns True. 

623 service_name: Human-readable label used in the error log 

624 (``Drive`` / ``Photos``). 

625 

626 Returns: 

627 True if it is safe to proceed; False to skip this sync cycle. 

628 """ 

629 if not required: 

630 return True 

631 all_present = True 

632 for destination_path in destinations: 

633 marker_path = os.path.join(destination_path, marker_filename) 

634 if not os.path.isfile(marker_path): 

635 LOGGER.error( 

636 f"{service_name} mount marker missing: {marker_path} not found — " 

637 f"refusing to sync. Create the marker file (`touch {marker_path}`) " 

638 f"after confirming the destination is correctly mounted, then the " 

639 f"next sync cycle will proceed.", 

640 ) 

641 all_present = False 

642 return all_present 

643 

644 

645def _list_local_files(destination_path: str) -> set[str] | None: 

646 """Every file under ``destination_path``; ``None`` if it can't be listed.""" 

647 files = set() 

648 if not os.path.exists(destination_path): 

649 return files 

650 try: 

651 for root, _dirs, file_list in os.walk(destination_path): 

652 for file in file_list: 

653 files.add(os.path.join(root, file)) 

654 except Exception: # noqa: BLE001 - stats are advisory 

655 return None 

656 return files 

657 

658 

659def _perform_drive_sync(config, api, sync_state: SyncState, drive_sync_interval: int): 

660 """ 

661 Execute drive synchronization if enabled. 

662 

663 Args: 

664 config: Configuration dictionary 

665 api: iCloud API instance 

666 sync_state: Current sync state 

667 drive_sync_interval: Drive sync interval in seconds 

668 

669 Returns: 

670 DriveStats object if sync was performed, None otherwise 

671 """ 

672 if config and "drive" in config and sync_state.enable_sync_drive: 

673 import time 

674 

675 from src.sync_stats import DriveStats 

676 

677 start_time = time.time() 

678 stats = DriveStats() 

679 

680 destination_path = config_parser.prepare_drive_destination(config=config) 

681 

682 # Mount-marker failsafe (see _check_mount_marker). Skip this 

683 # cycle when the marker isn't present. Reset the countdown to 

684 # the full interval so ``_calculate_next_sync_schedule`` waits 

685 # before re-checking -- without the reset, on startup 

686 # ``drive_time_remaining`` is 0 and the next iteration spins 

687 # at zero sleep into a tight busy loop that floods logs and 

688 # burns CPU until the user touches the marker. 

689 if not _check_mount_marker( 

690 destinations=[destination_path], 

691 marker_filename=config_parser.get_mount_marker_filename(config=config), 

692 required=config_parser.get_drive_require_mount_marker(config=config), 

693 service_name="Drive", 

694 ): 

695 sync_state.drive_time_remaining = drive_sync_interval 

696 return None 

697 

698 files_before = _list_local_files(destination_path) or set() 

699 

700 LOGGER.info("Syncing drive...") 

701 _publish_running("drive", True) 

702 try: 

703 files_after = sync_drive.sync_drive(config=config, drive=api.drive) 

704 finally: 

705 _publish_running("drive", False) 

706 LOGGER.info("Drive synced") 

707 

708 # Calculate statistics 

709 stats.duration_seconds = time.time() - start_time 

710 

711 # Handle case where sync_drive returns None (e.g., in tests) 

712 if files_after is not None: 

713 # Compare the disk with the disk. sync_drive's set also holds every 

714 # folder, and NFC-normalised names, so set against a listing of 

715 # files it counted every folder and every non-ASCII name as new 

716 # on every pass. 

717 local_after = _list_local_files(destination_path) 

718 if local_after is None: 

719 local_after = {f for f in files_after if not os.path.isdir(f)} 

720 

721 # Count newly downloaded files 

722 new_files = local_after - files_before 

723 stats.files_downloaded = len(new_files) 

724 

725 # Count skipped files 

726 stats.files_skipped = len(files_before & local_after) 

727 

728 # Count removed files 

729 if config_parser.get_drive_remove_obsolete(config=config): 

730 stats.files_removed = len(files_before - local_after) 

731 

732 # Calculate bytes downloaded 

733 try: 

734 for file_path in new_files: 

735 if os.path.exists(file_path) and os.path.isfile(file_path): 

736 stats.bytes_downloaded += os.path.getsize(file_path) 

737 except Exception: 

738 pass 

739 

740 # Reset countdown timer to the configured interval 

741 sync_state.drive_time_remaining = drive_sync_interval 

742 return stats 

743 return None 

744 

745 

746def _perform_photos_sync(config, api, sync_state: SyncState, photos_sync_interval: int): 

747 """ 

748 Execute photos synchronization if enabled. 

749 

750 Args: 

751 config: Configuration dictionary 

752 api: iCloud API instance 

753 sync_state: Current sync state 

754 photos_sync_interval: Photos sync interval in seconds 

755 

756 Returns: 

757 PhotoStats object if sync was performed, None otherwise 

758 """ 

759 if config and "photos" in config and sync_state.enable_sync_photos: 

760 import time 

761 

762 from src.sync_stats import PhotoStats 

763 

764 start_time = time.time() 

765 stats = PhotoStats() 

766 

767 destination_path = config_parser.prepare_photos_destination(config=config) 

768 

769 # Mount-marker failsafe (see _check_mount_marker). Skip this cycle 

770 # without advancing the countdown so the next interval re-checks 

771 # once the user fixes the mount + touches the marker file. 

772 if not _check_mount_marker( 

773 destinations=[destination_path], 

774 marker_filename=config_parser.get_mount_marker_filename(config=config), 

775 required=config_parser.get_photos_require_mount_marker(config=config), 

776 service_name="Photos", 

777 ): 

778 # Same busy-loop guard as the Drive branch above: reset the 

779 # countdown so the next cycle waits the configured interval 

780 # before re-checking the marker. 

781 sync_state.photos_time_remaining = photos_sync_interval 

782 return None 

783 

784 # Count files before sync 

785 files_before = set() 

786 if os.path.exists(destination_path): 

787 try: 

788 for root, _dirs, file_list in os.walk(destination_path): 

789 for file in file_list: 

790 files_before.add(os.path.join(root, file)) 

791 except Exception: 

792 pass 

793 

794 LOGGER.info("Syncing photos...") 

795 _publish_running("photos", True) 

796 try: 

797 sync_result = sync_photos.sync_photos(config=config, photos=api.photos) 

798 finally: 

799 _publish_running("photos", False) 

800 LOGGER.info("Photos synced") 

801 

802 # Count files after sync 

803 files_after = set() 

804 if os.path.exists(destination_path): 

805 try: 

806 for root, _dirs, file_list in os.walk(destination_path): 

807 for file in file_list: 

808 files_after.add(os.path.join(root, file)) 

809 except Exception: 

810 pass 

811 

812 # Calculate statistics 

813 stats.duration_seconds = time.time() - start_time 

814 

815 # Count newly downloaded files 

816 new_files = files_after - files_before 

817 stats.photos_downloaded = len(new_files) 

818 

819 # Estimate hardlinked photos (approximate) 

820 use_hardlinks = config_parser.get_photos_use_hardlinks( 

821 config=config, 

822 log_messages=False, 

823 ) 

824 if use_hardlinks: 

825 stats.photos_hardlinked = max( 

826 0, 

827 len(files_after) - len(files_before) - stats.photos_downloaded, 

828 ) 

829 

830 # Count skipped photos 

831 stats.photos_skipped = len(files_before & files_after) 

832 

833 # Calculate bytes downloaded 

834 try: 

835 for file_path in new_files: 

836 if os.path.exists(file_path) and os.path.isfile(file_path): 

837 stats.bytes_downloaded += os.path.getsize(file_path) 

838 

839 # Estimate bytes saved by hardlinks 

840 if use_hardlinks and stats.photos_hardlinked > 0: 

841 for file_path in files_after: 

842 if file_path not in new_files and os.path.isfile(file_path): 

843 stats.bytes_saved_by_hardlinks += os.path.getsize(file_path) 

844 except Exception: 

845 pass 

846 

847 # Track failed downloads so notifications reflect errors 

848 if isinstance(sync_result, tuple): 

849 _, failed_downloads = sync_result 

850 if failed_downloads > 0: 

851 stats.errors.append(f"{failed_downloads} photo download(s) failed") 

852 

853 # Get list of synced albums (simple approximation based on directories) 

854 try: 

855 for item in os.listdir(destination_path): 

856 item_path = os.path.join(destination_path, item) 

857 if os.path.isdir(item_path): 

858 stats.albums_synced.append(item) 

859 except Exception: 

860 pass 

861 

862 # Reset countdown timer to the configured interval 

863 sync_state.photos_time_remaining = photos_sync_interval 

864 return stats 

865 return None 

866 

867 

868def _perform_dry_run(config, api, check_files: int | None = None) -> None: 

869 """Authenticate-and-enumerate path used when ``--dry-run`` is passed. 

870 

871 Verifies that the configured credentials, mount paths, and iCloud-side 

872 state are all in working order WITHOUT writing or downloading any 

873 files. Designed as the safety check users run before letting the real 

874 sync loop loose on a new install. 

875 

876 Logs (at INFO level): 

877 - Drive destination path + root-level item count (when Drive is configured) 

878 - Photos destination path + library names (when Photos is configured) 

879 - When ``check_files`` is not None: per-library would-skip / 

880 size-mismatch / not-found counts (see ``migration_check``). 

881 

882 Args: 

883 config: Configuration dictionary 

884 api: Authenticated iCloud API instance 

885 check_files: When set (``--check-files=N``), additionally walks 

886 up to N photos per library and reports what a real sync 

887 would do per file. ``0`` walks every photo. ``None`` skips 

888 this check (cheap default for ``--dry-run`` alone). 

889 

890 Notifications, usage statistics, file writes, file deletions, and the 

891 sync loop itself are all skipped. 

892 """ 

893 LOGGER.info("DRY RUN: authentication succeeded — verifying configured services.") 

894 

895 if config and "drive" in config: 

896 try: 

897 # Resolved absolute path (root + destination), computed without 

898 # creating anything, so users can verify the mount point. Mirrors 

899 # how migration_check builds its base path. 

900 drive_destination = os.path.join( 

901 config_parser.get_root_destination_path(config=config), 

902 config_parser.get_drive_destination_path(config=config), 

903 ) 

904 LOGGER.info(f"DRY RUN: Drive destination: {drive_destination}") 

905 root_items = list(api.drive.dir()) 

906 LOGGER.info( 

907 f"DRY RUN: Drive root contains {len(root_items)} item(s) — " 

908 "real sync would walk this tree per `drive.filters`.", 

909 ) 

910 except Exception as e: 

911 LOGGER.warning(f"DRY RUN: Drive enumeration failed: {e!s}") 

912 else: 

913 LOGGER.info( 

914 "DRY RUN: no `drive:` section in config — Drive sync would be skipped.", 

915 ) 

916 

917 if config and "photos" in config: 

918 try: 

919 photos_destination = os.path.join( 

920 config_parser.get_root_destination_path(config=config), 

921 config_parser.get_photos_destination_path(config=config), 

922 ) 

923 LOGGER.info(f"DRY RUN: Photos destination: {photos_destination}") 

924 libraries = ( 

925 list(api.photos.libraries.keys()) 

926 if hasattr(api.photos, "libraries") 

927 else [] 

928 ) 

929 if libraries: 

930 LOGGER.info( 

931 f"DRY RUN: Photos libraries available: {', '.join(libraries)}", 

932 ) 

933 else: 

934 LOGGER.info("DRY RUN: Photos libraries: (none reported by iCloud)") 

935 except Exception as e: 

936 LOGGER.warning(f"DRY RUN: Photos enumeration failed: {e!s}") 

937 else: 

938 LOGGER.info( 

939 "DRY RUN: no `photos:` section in config — Photos sync would be skipped.", 

940 ) 

941 

942 if check_files is not None: 

943 from src import migration_check 

944 

945 # Photos walker — per-library counts using mandarons' real path/size 

946 # logic so the report mirrors what a real sync would skip vs download. 

947 if config and "photos" in config: 

948 try: 

949 LOGGER.info( 

950 f"DRY RUN: walking photos for file-existence check " 

951 f"(--check-files={'all' if check_files == 0 else check_files} per library) ...", 

952 ) 

953 results = migration_check.check_migration( 

954 api=api, 

955 config=config, 

956 sample=check_files, 

957 ) 

958 for library_name, result in results.items(): 

959 stats = result["stats"] 

960 LOGGER.info( 

961 f"DRY RUN: {library_name} (dest {result['library_dest']}): " 

962 f"sampled={result['checked']} " 

963 f"would_skip={stats['would_skip']} " 

964 f"size_mismatch={stats['size_mismatch']} " 

965 f"not_found={stats['not_found']} " 

966 f"errors={stats['error']}", 

967 ) 

968 for status, items in result["samples"].items(): 

969 for item in items: 

970 if status == "size_mismatch": 

971 path, expected, actual = item 

972 LOGGER.info( 

973 f"DRY RUN: sample {status}: {path} (have {actual:,}b, want {expected:,}b)", 

974 ) 

975 else: 

976 path, expected = item 

977 LOGGER.info( 

978 f"DRY RUN: sample {status}: {path} ({expected:,}b)", 

979 ) 

980 except Exception as e: 

981 LOGGER.warning(f"DRY RUN: photos check-files walk failed: {e!s}") 

982 

983 # Drive walker — same per-file would_skip/size_mismatch/not_found 

984 # report, but walking the Drive tree (no library_destinations, 

985 # mirror-tree layout). Catches misconfigured drive.destination. 

986 if config and "drive" in config: 

987 try: 

988 drive_result = migration_check.check_drive_migration( 

989 api=api, 

990 config=config, 

991 sample=check_files, 

992 ) 

993 if drive_result is not None: 

994 stats = drive_result["stats"] 

995 LOGGER.info( 

996 f"DRY RUN: Drive (dest {drive_result['drive_destination']}): " 

997 f"sampled={drive_result['checked']} " 

998 f"would_skip={stats['would_skip']} " 

999 f"size_mismatch={stats['size_mismatch']} " 

1000 f"not_found={stats['not_found']} " 

1001 f"errors={stats['error']}", 

1002 ) 

1003 for status, items in drive_result["samples"].items(): 

1004 for item in items: 

1005 if status == "size_mismatch": 

1006 path, expected, actual = item 

1007 LOGGER.info( 

1008 f"DRY RUN: sample {status}: {path} (have {actual:,}b, want {expected:,}b)", 

1009 ) 

1010 else: 

1011 path, expected = item 

1012 LOGGER.info( 

1013 f"DRY RUN: sample {status}: {path} ({expected:,}b)", 

1014 ) 

1015 except Exception as e: 

1016 LOGGER.warning(f"DRY RUN: drive check-files walk failed: {e!s}") 

1017 

1018 LOGGER.info( 

1019 "DRY RUN complete — no files were written. Re-run without --dry-run to sync.", 

1020 ) 

1021 

1022 

1023def _check_services_configured(config): 

1024 """ 

1025 Check if any sync services are configured. 

1026 

1027 Args: 

1028 config: Configuration dictionary 

1029 

1030 Returns: 

1031 bool: True if at least one service is configured 

1032 """ 

1033 

1034 return "drive" in config or "photos" in config 

1035 

1036 

1037def _cycle_nothing_synced_reason(config, drive_stats, photos_stats) -> str | None: 

1038 """Why this cycle synced no service at all, or None if one did. 

1039 

1040 Such a cycle is indistinguishable from a clean one by its stats -- no 

1041 errors, no counts -- so reporting it as a success is how a monitor stays 

1042 green while nothing whatsoever is being downloaded. It happens two ways: 

1043 nothing is configured to sync, or every service that was due got skipped 

1044 by the mount-marker failsafe. 

1045 

1046 Not to be confused with a service that simply was not due. With unequal 

1047 intervals ``_calculate_next_sync_schedule`` enables only the service 

1048 whose timer expired, so one of the two returning None is the ordinary 

1049 case -- hence "no stats at all" rather than "any stats missing". 

1050 

1051 Args: 

1052 config: Configuration dictionary 

1053 drive_stats: Result of ``_perform_drive_sync`` 

1054 photos_stats: Result of ``_perform_photos_sync`` 

1055 

1056 Returns: 

1057 ``nothing_synced``, ``mount_marker_missing``, or None if a service ran 

1058 """ 

1059 if not _check_services_configured(config): 

1060 return "nothing_synced" 

1061 if drive_stats is None and photos_stats is None: 

1062 return "mount_marker_missing" 

1063 return None 

1064 

1065 

1066def _cycle_end_message(has_errors: bool, nothing_reason: str | None) -> str: 

1067 """The human text for the end-of-cycle event. 

1068 

1069 Kept out of ``sync()`` only because the branch it sits in is already four 

1070 levels deep. 

1071 """ 

1072 if nothing_reason == "nothing_synced": 

1073 return "iCloud sync cycle synced nothing: no drive or photos section is configured" 

1074 if nothing_reason: 

1075 return "iCloud sync cycle synced nothing: the mount marker is missing" 

1076 if has_errors: 

1077 return "iCloud sync cycle completed with errors" 

1078 return "iCloud sync cycle completed" 

1079 

1080 

1081def _send_usage_statistics(config, summary: SyncSummary) -> None: 

1082 """Send anonymized usage statistics. 

1083 

1084 Args: 

1085 config: Configuration dictionary 

1086 summary: Sync summary with statistics 

1087 """ 

1088 

1089 # Create anonymized usage data 

1090 usage_data = { 

1091 "sync_duration": ( 

1092 (summary.sync_end_time - summary.sync_start_time).total_seconds() 

1093 if summary.sync_end_time 

1094 else 0 

1095 ), 

1096 "has_drive_activity": bool( 

1097 summary.drive_stats and summary.drive_stats.has_activity(), 

1098 ), 

1099 "has_photos_activity": bool( 

1100 summary.photo_stats and summary.photo_stats.has_activity(), 

1101 ), 

1102 "has_errors": summary.has_errors(), 

1103 "timestamp": ( 

1104 summary.sync_end_time.isoformat() if summary.sync_end_time else None 

1105 ), 

1106 } 

1107 

1108 # Add aggregated statistics (no personal data) 

1109 if summary.drive_stats: 

1110 usage_data["drive"] = { 

1111 "files_count": summary.drive_stats.files_downloaded, 

1112 "bytes_count": summary.drive_stats.bytes_downloaded, 

1113 "has_errors": summary.drive_stats.has_errors(), 

1114 } 

1115 

1116 if summary.photo_stats: 

1117 usage_data["photos"] = { 

1118 "photos_count": summary.photo_stats.photos_downloaded, 

1119 "bytes_count": summary.photo_stats.bytes_downloaded, 

1120 "hardlinks_count": summary.photo_stats.photos_hardlinked, 

1121 "has_errors": summary.photo_stats.has_errors(), 

1122 } 

1123 

1124 # Send to usage tracking 

1125 alive(config=config, data=usage_data) 

1126 

1127 

1128def _auth_retry_sleep(total_seconds: int) -> None: 

1129 """Wait between sign-in attempts, ending early on a completed re-auth. 

1130 

1131 The loop backs off for ``retry_login_interval`` between attempts and 

1132 cannot otherwise see that the session was fixed underneath it, so 

1133 someone who signs in through the web UI watches the dashboard keep 

1134 saying the sync is stopped until an interval that began *before* the 

1135 problem was solved finally runs out. 

1136 

1137 Polls only the re-auth signal, not the force-sync sentinel behind 

1138 "Sync now": that button means "sync everything now", and a re-auth 

1139 should end a wait without also queueing a full re-enumeration. 

1140 """ 

1141 _CHUNK = 2 

1142 try: 

1143 from src import web_signals as _ws 

1144 except ImportError: # pragma: no cover - module is optional 

1145 sleep(total_seconds) 

1146 return 

1147 

1148 if total_seconds <= _CHUNK: 

1149 sleep(total_seconds) 

1150 return 

1151 

1152 remaining = total_seconds 

1153 while remaining > 0: 

1154 chunk = min(_CHUNK, remaining) 

1155 sleep(chunk) 

1156 remaining -= chunk 

1157 if _ws.consume_reauth_completed(): 

1158 LOGGER.info("Re-auth completed -- ending the retry wait early.") 

1159 return 

1160 

1161 

1162def _request_2fa_push_once(api, sync_state: SyncState) -> None: 

1163 """Ask Apple to push a 2FA code to the trusted devices, once per episode. 

1164 

1165 Without this call the loop notified the user that re-auth was needed but 

1166 never requested a code, so nothing was ever sent. 

1167 

1168 The latch is set only when Apple accepts the request. 

1169 ``trigger_2fa_push_notification`` returns False rather than raising for 

1170 most failures, and latching regardless meant one transient error 

1171 forfeited the push for the whole episode -- the user told "2FA is 

1172 required" while no code ever arrived, which is the bug this exists to 

1173 fix. Retrying on the next cycle is bounded by ``retry_login_interval`` 

1174 (600s by default), far below anything that trips Apple's limits. 

1175 

1176 Best-effort: a failure here never stops the retry loop. 

1177 """ 

1178 if sync_state.two_fa_triggered: 

1179 return 

1180 try: 

1181 pushed = api.trigger_2fa_push_notification() 

1182 except Exception as e: # noqa: BLE001 

1183 LOGGER.warning(f"Failed to request 2FA push notification; will retry next cycle: {e!s}") 

1184 return 

1185 if pushed: 

1186 LOGGER.info("Requested a 2FA push notification to your trusted devices.") 

1187 sync_state.two_fa_triggered = True 

1188 else: 

1189 LOGGER.warning("Apple did not accept the 2FA push request; will retry next cycle.") 

1190 

1191 

1192def _handle_2fa_required(config, username: str, sync_state: SyncState, api): 

1193 """ 

1194 Handle 2FA authentication requirement. 

1195 

1196 Args: 

1197 config: Configuration dictionary 

1198 username: iCloud username 

1199 sync_state: Current sync state 

1200 api: Live ``ICloudPyService`` still in its 2FA-required state. Used to 

1201 request a push notification to the user's trusted devices. When 

1202 ``app.telegram.listen`` is true, the retry sleep is replaced with a 

1203 Telegram poll: the user replies the auth keyword to have Apple push a 

1204 code, then replies the 6 digits -- completing re-authentication from a 

1205 phone, headless, with no web UI. 

1206 

1207 Returns: 

1208 bool: True if should continue (retry), False if should exit 

1209 """ 

1210 LOGGER.error("Error: 2FA is required. Please log in.") 

1211 _publish_auth_blocked(True, reason="2fa_required") 

1212 # Decided before anything is sent: it selects the notification wording, 

1213 # the reason a receiver sees, and suppresses two steps that cannot 

1214 # succeed on such an account. 

1215 security_key = _detect_security_key_account(api, username) 

1216 notify.send_cycle_event( 

1217 config=config, 

1218 boundary="failure", 

1219 message="iCloud sync cycle aborted: 2FA is required", 

1220 data={"reason": "security_key_required" if security_key else "two_factor_required"}, 

1221 ) 

1222 if security_key: 

1223 LOGGER.error( 

1224 "This account signs in with a security key, so Apple will not " 

1225 "send a 6-digit code. Complete the ceremony on the dashboard " 

1226 "(/auth); the push request and the code listener are skipped.", 

1227 ) 

1228 # Ask Apple to push a code before anything else -- including the exit 

1229 # below: retry_login_interval < 0 is the mode where an operator is about 

1230 # to intervene by hand, and a code on their devices is what they need. 

1231 # Not for a security-key account: Apple sends those no code at all. 

1232 if not security_key: 

1233 _request_2fa_push_once(api, sync_state) 

1234 

1235 sleep_for = config_parser.get_retry_login_interval(config=config) 

1236 

1237 if sleep_for < 0: 

1238 LOGGER.info("retry_login_interval is < 0, exiting ...") 

1239 return False 

1240 

1241 _log_retry_time(sleep_for) 

1242 server_region = config_parser.get_region(config=config) 

1243 # notify.send is throttled (once per 24h) and listen-aware: in listen mode the 

1244 # Telegram channel gets the actionable reply prompt, other channels the standard 

1245 # alert. Throttling here is what prevents a "reply auth" message every retry cycle. 

1246 sync_state.last_send = notify.send( 

1247 config=config, 

1248 username=username, 

1249 last_send=sync_state.last_send, 

1250 region=server_region, 

1251 dashboard_url=_resolve_dashboard_url(config), 

1252 # A security-key account cannot finish sign-in from a Telegram code, 

1253 # so it gets the standard alert pointing at the dashboard. 

1254 reply_prompt=not security_key, 

1255 event="security_key_required" if security_key else "two_factor_required", 

1256 ) 

1257 if not security_key and config_parser.get_telegram_listen_enabled(config=config): 

1258 _wait_for_telegram_code(config=config, api=api, timeout_seconds=sleep_for) 

1259 else: 

1260 _auth_retry_sleep(sleep_for) 

1261 return True 

1262 

1263 

1264def _wait_for_telegram_code(config, api, timeout_seconds: int) -> bool: 

1265 """Drive 2FA over Telegram with a manual, user-initiated trigger. 

1266 

1267 The reply prompt itself is sent by ``notify.send`` (throttled); this function 

1268 drains any stale replies, then polls for the user's actions: 

1269 1. On the auth keyword -> ``api.trigger_2fa_push_notification()`` so Apple 

1270 actually pushes a code to the trusted devices. (The headless path 

1271 previously waited for a code it never requested -- this missing trigger 

1272 is the core bug this fixes.) 

1273 2. On a 6-digit reply (spaces/dashes tolerated) -> ``validate_2fa_code`` 

1274 + ``trust_session``. 

1275 

1276 Returns True once a code validates and trust succeeds within 

1277 ``timeout_seconds``, or once the web UI completes the re-auth first; 

1278 False on timeout. Best-effort throughout. The Telegram 

1279 ``getUpdates`` offset is held in-memory for the duration of this wait. 

1280 """ 

1281 from src import web_signals 

1282 

1283 poll_interval = 5 

1284 bot_token = config_parser.get_telegram_bot_token(config=config) 

1285 chat_id = config_parser.get_telegram_chat_id(config=config) 

1286 auth_keyword = config_parser.get_telegram_auth_keyword(config=config) 

1287 if not bot_token or not chat_id: 

1288 LOGGER.warning( 

1289 "Telegram listen enabled but bot_token/chat_id not configured; falling back to plain sleep.", 

1290 ) 

1291 sleep(timeout_seconds) 

1292 return False 

1293 

1294 # Drain any messages already pending so a stale reply from a previous 

1295 # session does not get acted on; start listening for genuinely new replies. 

1296 # Deliberate trade-off: a code typed while the loop is between wait 

1297 # windows is dropped too. Acting on an old code is worse than asking for 

1298 # a fresh one, and the window is the whole retry interval (600s default). 

1299 _, offset = notify.poll_telegram_for_text( 

1300 bot_token=bot_token, chat_id=chat_id, offset=0, 

1301 ) 

1302 while True: 

1303 _, drained = notify.poll_telegram_for_text( 

1304 bot_token=bot_token, chat_id=chat_id, offset=offset, 

1305 ) 

1306 if drained == offset: 

1307 break 

1308 offset = drained 

1309 

1310 LOGGER.info( 

1311 f"Listening on Telegram for '{auth_keyword}' trigger or 6-digit code (timeout {timeout_seconds}s).", 

1312 ) 

1313 elapsed = 0 

1314 while elapsed < timeout_seconds: 

1315 chunk = min(poll_interval, timeout_seconds - elapsed) 

1316 sleep(chunk) 

1317 elapsed += chunk 

1318 # The web UI and Telegram can both complete a re-auth. If the web UI 

1319 # got there first, stop listening -- otherwise the loop sits out the 

1320 # rest of the window holding a session that is already fixed. 

1321 if web_signals.consume_reauth_completed(): 

1322 LOGGER.info("Re-auth completed in the web UI -- ending the Telegram wait.") 

1323 return True 

1324 text, offset = notify.poll_telegram_for_text( 

1325 bot_token=bot_token, 

1326 chat_id=chat_id, 

1327 offset=offset, 

1328 ) 

1329 if not text: 

1330 continue 

1331 norm = text.strip().lower() 

1332 if norm == auth_keyword: 

1333 LOGGER.info("Telegram auth trigger received -- requesting 2FA push.") 

1334 try: 

1335 pushed = api.trigger_2fa_push_notification() 

1336 except Exception as e: # noqa: BLE001 

1337 LOGGER.warning(f"trigger_2fa_push_notification raised: {e!s}") 

1338 pushed = False 

1339 notify.post_message_to_telegram( 

1340 bot_token, 

1341 chat_id, 

1342 ( 

1343 "✅ 2FA code sent to your Apple devices -- reply the 6-digit code here." 

1344 if pushed 

1345 else "⚠️ Couldn't request a code (no trusted device, or auth state off). Try again shortly." 

1346 ), 

1347 ) 

1348 continue 

1349 code = norm.replace(" ", "").replace("-", "") 

1350 if re.fullmatch(r"\d{6}", code): 

1351 LOGGER.info("Received 6-digit code via Telegram -- validating.") 

1352 try: 

1353 accepted = api.validate_2fa_code(code) 

1354 except Exception as e: # noqa: BLE001 

1355 LOGGER.warning( 

1356 f"validate_2fa_code raised: {e!s} -- waiting for another code.", 

1357 ) 

1358 continue 

1359 if not accepted: 

1360 notify.post_message_to_telegram( 

1361 bot_token, 

1362 chat_id, 

1363 "❌ Apple rejected that code -- reply a fresh one.", 

1364 ) 

1365 LOGGER.warning( 

1366 "Apple rejected the Telegram-supplied code -- waiting for another.", 

1367 ) 

1368 continue 

1369 try: 

1370 api.trust_session() 

1371 except Exception as e: # noqa: BLE001 

1372 LOGGER.warning(f"trust_session raised (non-fatal): {e!s}") 

1373 notify.post_message_to_telegram( 

1374 bot_token, 

1375 chat_id, 

1376 "✅ Re-authenticated. iCloud sync resumed.", 

1377 ) 

1378 LOGGER.info("Telegram-driven 2FA succeeded; resuming sync.") 

1379 return True 

1380 LOGGER.info("Telegram listen timeout reached with no usable code; retrying auth.") 

1381 return False 

1382 

1383 

1384def _needs_a_human(sync_state: SyncState, error) -> bool: 

1385 """Whether a sign-in failure warrants the "re-auth required" alert. 

1386 

1387 A rejected password always does: retrying cannot fix it. 

1388 

1389 In session-only mode one more case does, because it cannot be told 

1390 apart from a rejected session. icloudpy keeps the HTTP status on the 

1391 exception only for a non-JSON body or its own re-auth statuses 

1392 (``_SESSION_REJECTED_CODES``), so a JSON-bodied 401 arrives with 

1393 ``code`` as ``None``. Those are the ones that would otherwise leave a 

1394 container only a human can revive retrying in silence forever. 

1395 

1396 Everything else is an outage -- a 5xx that kept its status, a dropped 

1397 connection, a DNS failure -- and says nothing about the session. Those 

1398 are logged and retried. Waking someone daily to re-authenticate over 

1399 Apple having a bad hour is the alert this function exists to withhold. 

1400 """ 

1401 if isinstance(error, exceptions.ICloudPyFailedLoginException): 

1402 return True 

1403 return ( 

1404 sync_state.session_only 

1405 and isinstance(error, exceptions.ICloudPyAPIResponseException) 

1406 and error.code is None 

1407 ) 

1408 

1409 

1410def _handle_auth_transport_error(config, username: str, sync_state: SyncState, error): 

1411 """Back off after a sign-in failure Apple did not express as a 2FA prompt. 

1412 

1413 Uses at least ``_AUTH_BACKOFF_FLOOR_SEC`` regardless of the configured 

1414 retry interval: the errors that land here (notably Apple's 409 on 

1415 ``/signin/init``) mean "you are trying too often", so honouring a short 

1416 interval would make it worse. 

1417 

1418 Returns True to keep looping, False to exit. 

1419 """ 

1420 LOGGER.error(f"Sign-in failed and will be retried: {error!s}") 

1421 # sign_in_failed is reserved for what the alert below treats as needing 

1422 # a human. A network fault or an Apple service error means the attempt 

1423 # never completed, which needs no one to intervene. 

1424 rejected = _needs_a_human(sync_state, error) 

1425 notify.send_cycle_event( 

1426 config=config, 

1427 boundary="failure", 

1428 message=( 

1429 "iCloud sync cycle aborted: sign-in failed" 

1430 if rejected 

1431 else "iCloud sync cycle aborted: sign-in did not complete" 

1432 ), 

1433 data={"reason": "sign_in_failed" if rejected else "sign_in_error"}, 

1434 ) 

1435 sleep_for = config_parser.get_retry_login_interval(config=config) 

1436 if sleep_for < 0: 

1437 LOGGER.info("retry_login_interval is < 0, exiting ...") 

1438 return False 

1439 sleep_for = max(sleep_for, _AUTH_BACKOFF_FLOOR_SEC) 

1440 _log_retry_time(sleep_for) 

1441 if sync_state.session_only: 

1442 # The loop is not syncing and only a human can change that, so the 

1443 # dashboard is told -- its wording for this reason allows for an 

1444 # outage and asks for nothing. 

1445 _publish_auth_blocked(True, reason="sign_in_failed") 

1446 if rejected: 

1447 # notify.send's text is "iCloud re-auth required", so it is reserved 

1448 # for the cases where that is actually true: a rejected password, 

1449 # which never heals by retrying, and -- in session-only mode -- a 

1450 # failure that cannot be told apart from a rejected session. It is 

1451 # throttled, so this is not a message per retry. 

1452 sync_state.last_send = notify.send( 

1453 config=config, 

1454 username=username, 

1455 last_send=sync_state.last_send, 

1456 region=config_parser.get_region(config=config), 

1457 dashboard_url=_resolve_dashboard_url(config), 

1458 event="sign_in_failed", 

1459 ) 

1460 # Ends early on a completed web-UI re-auth, but not on "Sync now": 

1461 # nothing a button does may shorten a throttle backoff. 

1462 _auth_retry_sleep(sleep_for) 

1463 return True 

1464 

1465 

1466def _handle_sync_error(config, error, drive_sync_interval, photos_sync_interval): 

1467 """Back off after a failure that happened *after* a successful sign-in. 

1468 

1469 Anything raised once ``api`` exists is a service problem, not an auth 

1470 problem: a zone that is unavailable, a 5xx on a download, a connection 

1471 dropped mid-transfer. Reporting those as sign-in failures sends the user 

1472 to re-authenticate for no reason. 

1473 

1474 The interval matters as much as the wording. Every handler here ends in 

1475 ``continue``, which skips ``_calculate_next_sync_schedule`` -- so the 

1476 countdown timers never advance and both services stay enabled. Retrying 

1477 on the short login interval therefore re-enumerates the whole library 

1478 every few minutes. Wait at least as long as the shortest configured sync 

1479 interval instead: never poll a broken service faster than a working one. 

1480 

1481 Returns True to keep looping, False to exit. 

1482 """ 

1483 LOGGER.error(f"Sync failed and will be retried: {error!s}") 

1484 notify.send_cycle_event( 

1485 config=config, 

1486 boundary="failure", 

1487 message="iCloud sync cycle failed and will be retried", 

1488 data={"reason": "sync_error"}, 

1489 ) 

1490 # log_messages=False: this is not a login retry, and the getter's 

1491 # "Retrying login every N seconds." would say otherwise. 

1492 sleep_for = config_parser.get_retry_login_interval(config=config, log_messages=False) 

1493 if sleep_for < 0: 

1494 LOGGER.info("retry_login_interval is < 0, exiting ...") 

1495 return False 

1496 configured = [i for i in (drive_sync_interval, photos_sync_interval) if i > 0] 

1497 if configured: 

1498 sleep_for = max(sleep_for, min(configured)) 

1499 _log_retry_time(sleep_for, what="sync") 

1500 # This can be a whole sync interval; the "Sync now" button must still 

1501 # cut it short, as it does on the normal scheduling path. 

1502 _interruptible_sleep(sleep_for) 

1503 return True 

1504 

1505 

1506def _handle_password_error(config, username: str, sync_state: SyncState, error): 

1507 """ 

1508 Handle password not available error. 

1509 

1510 Args: 

1511 config: Configuration dictionary 

1512 username: iCloud username 

1513 sync_state: Current sync state 

1514 error: The raised exception, whose message names which way 

1515 session-only mode failed -- no session at all, or a session 

1516 Apple no longer accepts. 

1517 

1518 Returns: 

1519 bool: True if should continue (retry), False if should exit 

1520 """ 

1521 LOGGER.error(str(error)) 

1522 # The dashboard's own on-disk check reads an empty keyring as "setup 

1523 # needed", which is the wrong instruction here: the session, not the 

1524 # password, is what has to be replaced. 

1525 _publish_auth_blocked(True, reason="session_unusable") 

1526 notify.send_cycle_event( 

1527 config=config, 

1528 boundary="failure", 

1529 message="iCloud sync cycle aborted: no stored password and no usable saved session", 

1530 data={"reason": "password_missing"}, 

1531 ) 

1532 sleep_for = config_parser.get_retry_login_interval(config=config) 

1533 

1534 if sleep_for < 0: 

1535 LOGGER.info("retry_login_interval is < 0, exiting ...") 

1536 return False 

1537 

1538 _log_retry_time(sleep_for) 

1539 server_region = config_parser.get_region(config=config) 

1540 sync_state.last_send = notify.send( 

1541 config=config, 

1542 username=username, 

1543 last_send=sync_state.last_send, 

1544 region=server_region, 

1545 dashboard_url=_resolve_dashboard_url(config), 

1546 event="password_missing", 

1547 ) 

1548 _auth_retry_sleep(sleep_for) 

1549 return True 

1550 

1551 

1552def _log_retry_time(sleep_for: int, what: str = "login"): 

1553 """ 

1554 Log the next retry time. 

1555 

1556 Args: 

1557 sleep_for: Sleep duration in seconds 

1558 what: What is being retried; a failed sync is not a failed login 

1559 """ 

1560 next_sync = ( 

1561 datetime.datetime.now() + datetime.timedelta(seconds=sleep_for) 

1562 ).strftime("%c") 

1563 LOGGER.info(f"Retrying {what} at {next_sync} ...") 

1564 

1565 

1566def _calculate_next_sync_schedule(config, sync_state: SyncState): 

1567 """ 

1568 Calculate next sync schedule and update sync state. 

1569 

1570 This function implements the adaptive scheduling algorithm that determines 

1571 which service should sync next based on countdown timers. 

1572 

1573 Args: 

1574 config: Configuration dictionary 

1575 sync_state: Current sync state 

1576 

1577 Returns: 

1578 int: Sleep duration in seconds 

1579 """ 

1580 has_drive = config and "drive" in config 

1581 has_photos = config and "photos" in config 

1582 

1583 if not has_drive and has_photos: 

1584 sleep_for = sync_state.photos_time_remaining 

1585 sync_state.enable_sync_drive = False 

1586 sync_state.enable_sync_photos = True 

1587 elif has_drive and not has_photos: 

1588 sleep_for = sync_state.drive_time_remaining 

1589 sync_state.enable_sync_drive = True 

1590 sync_state.enable_sync_photos = False 

1591 else: 

1592 # Sleep until the sooner of the two is due, and take that time off 

1593 # both countdowns. Whichever reaches zero syncs next; equal timers 

1594 # sync together. A negative countdown is a one-shot service 

1595 # (sync_interval < 0) that has already run: it is never due again, 

1596 # so it takes no part, and must never become a negative sleep. 

1597 pending = [t for t in (sync_state.drive_time_remaining, sync_state.photos_time_remaining) if t >= 0] 

1598 sleep_for = min(pending) if pending else 0 

1599 if sync_state.drive_time_remaining >= 0: 

1600 sync_state.drive_time_remaining -= sleep_for 

1601 if sync_state.photos_time_remaining >= 0: 

1602 sync_state.photos_time_remaining -= sleep_for 

1603 sync_state.enable_sync_drive = sync_state.drive_time_remaining == 0 

1604 sync_state.enable_sync_photos = sync_state.photos_time_remaining == 0 

1605 

1606 return sleep_for 

1607 

1608 

1609def _log_next_sync_time(sleep_for: int): 

1610 """ 

1611 Log the next scheduled sync time. 

1612 

1613 Args: 

1614 sleep_for: Sleep duration in seconds 

1615 """ 

1616 next_sync = ( 

1617 datetime.datetime.now() + datetime.timedelta(seconds=sleep_for) 

1618 ).strftime("%c") 

1619 LOGGER.info(f"Resyncing at {next_sync} ...") 

1620 

1621 

1622def _log_sync_intervals_at_startup(config): 

1623 """ 

1624 Log sync intervals once at startup. 

1625 

1626 Args: 

1627 config: Configuration dictionary 

1628 """ 

1629 if config and "drive" in config: 

1630 config_parser.get_drive_sync_interval(config=config, log_messages=True) 

1631 if config and "photos" in config: 

1632 config_parser.get_photos_sync_interval(config=config, log_messages=True) 

1633 

1634 

1635def _should_exit_oneshot_mode(config): 

1636 """ 

1637 Check if should exit in oneshot mode. 

1638 

1639 Oneshot mode exits when ALL configured sync intervals are negative. 

1640 

1641 Args: 

1642 config: Configuration dictionary 

1643 

1644 Returns: 

1645 bool: True if should exit 

1646 """ 

1647 

1648 should_exit_drive = ("drive" not in config) or ( 

1649 config_parser.get_drive_sync_interval(config=config, log_messages=False) < 0 

1650 ) 

1651 should_exit_photos = ("photos" not in config) or ( 

1652 config_parser.get_photos_sync_interval(config=config, log_messages=False) < 0 

1653 ) 

1654 

1655 return should_exit_drive and should_exit_photos 

1656 

1657 

1658def sync(dry_run: bool = False, check_files: int | None = None): 

1659 """ 

1660 Main synchronization loop. 

1661 

1662 Orchestrates the entire sync process by delegating specific responsibilities 

1663 to focused helper functions. This function coordinates the high-level flow 

1664 while each helper handles a single concern. 

1665 

1666 Args: 

1667 dry_run: When True, authenticate and summarise what would be synced, 

1668 then exit without writing files, sending notifications, or 

1669 entering the sync loop. Useful for verifying credentials, mount 

1670 paths, and config before the real loop starts downloading. 

1671 check_files: Optional sample size for the per-photo file-existence 

1672 check during dry-run. Only meaningful with ``dry_run=True``. 

1673 ``None`` skips the check (cheap default). ``0`` walks every 

1674 photo (slow on large libraries). Positive N walks N 

1675 stride-sampled photos per library. 

1676 """ 

1677 sync_state = SyncState() 

1678 startup_logged = False 

1679 

1680 while True: 

1681 # A config that cannot be read must not kill the daemon. On a NAS the 

1682 # volume holding config.yaml can lag behind container start or go away 

1683 # mid-run, and a half-written file (the user editing it live) raises 

1684 # out of the YAML parser. Either way the traceback escapes the loop, 

1685 # and `restart: unless-stopped` turns that into a restart loop. 

1686 try: 

1687 config = _load_configuration() 

1688 except Exception as e: # noqa: BLE001 -- any parse fault must not be fatal 

1689 LOGGER.error(f"Config file could not be read, retrying: {e!s}") 

1690 config = None 

1691 if config is None: 

1692 if dry_run: 

1693 # A dry run is a one-shot check with nothing to wait for. 

1694 LOGGER.error("DRY RUN: no readable config, nothing to check.") 

1695 return 

1696 sleep(DEFAULT_RETRY_LOGIN_INTERVAL_SEC) 

1697 continue 

1698 

1699 # Log sync intervals once at startup 

1700 if not startup_logged: 

1701 _log_sync_intervals_at_startup(config) 

1702 notify.warn_unknown_webhook_events(config) 

1703 # The state file outlives the container, so a restart mid-library 

1704 # would leave the dashboard showing it as still syncing. Nothing 

1705 # can legitimately be in flight here. 

1706 try: 

1707 from src import web_signals as _ws 

1708 

1709 _ws.clear_stale_library_states() 

1710 except Exception as e: # noqa: BLE001 -- never block startup 

1711 LOGGER.debug(f"web_signals: clear_stale_library_states raised: {e!s}") 

1712 startup_logged = True 

1713 

1714 drive_sync_interval, photos_sync_interval = _extract_sync_intervals( 

1715 config, 

1716 log_messages=False, 

1717 ) 

1718 username = config_parser.get_username(config=config) if config else None 

1719 

1720 # Web UI "Sync now" requests: ``src.web_signals`` writes a 

1721 # sentinel file when the user taps the button; we delete it and 

1722 # zero the countdown so the next pass through the sync calls 

1723 # runs immediately. Best-effort import so vanilla mandarons 

1724 # builds without the web-UI module still work. 

1725 try: 

1726 from src import web_signals as _ws 

1727 

1728 if _ws.consume_force_sync("drive"): 

1729 LOGGER.info("Force-sync requested for Drive — running immediately") 

1730 sync_state.drive_time_remaining = 0 

1731 if _ws.consume_force_sync("photos"): 

1732 LOGGER.info("Force-sync requested for Photos — running immediately") 

1733 sync_state.photos_time_remaining = 0 

1734 except ( 

1735 ImportError 

1736 ): # pragma: no cover — best-effort fallback for builds without web_signals 

1737 pass 

1738 

1739 if username: 

1740 authenticated = False 

1741 try: 

1742 api = _authenticate_and_get_api(config, username, sync_state) 

1743 authenticated = True 

1744 

1745 # Dry-run path: authenticate, enumerate, log, exit. 

1746 # Skips the entire sync + notification + retry pipeline. 

1747 if dry_run: 

1748 if api.requires_2sa: 

1749 LOGGER.info( 

1750 "DRY RUN: 2FA required — finish interactive auth first " 

1751 "(see README), then re-run with --dry-run.", 

1752 ) 

1753 else: 

1754 _perform_dry_run(config, api, check_files=check_files) 

1755 return 

1756 

1757 _publish_auth_blocked(False) 

1758 if not api.requires_2sa: 

1759 # Trust-window check: record current cookie expiry and 

1760 # fire a pre-emptive warning once if it's about to lapse. 

1761 # Best-effort: any failure is logged + swallowed inside. 

1762 _maybe_refresh_trust(config, api) 

1763 _maybe_warn_trust_expiring(config, api, username) 

1764 

1765 # Authenticated: clear the 2FA trigger latch so a future 

1766 # re-auth episode requests a fresh push exactly once. 

1767 sync_state.two_fa_triggered = False 

1768 

1769 # Signed in and about to sync: open the cycle on any 

1770 # configured webhook. Fire-and-forget, and a no-op when 

1771 # none is configured (see notify.send_cycle_event). 

1772 notify.send_cycle_event( 

1773 config=config, 

1774 boundary="start", 

1775 message="iCloud sync cycle started", 

1776 ) 

1777 

1778 # Create summary for this sync cycle 

1779 summary = SyncSummary() 

1780 

1781 # Perform syncs and collect statistics 

1782 drive_stats = _perform_drive_sync( 

1783 config, 

1784 api, 

1785 sync_state, 

1786 drive_sync_interval, 

1787 ) 

1788 photos_stats = _perform_photos_sync( 

1789 config, 

1790 api, 

1791 sync_state, 

1792 photos_sync_interval, 

1793 ) 

1794 

1795 # Populate summary with statistics 

1796 summary.drive_stats = drive_stats 

1797 summary.photo_stats = photos_stats 

1798 summary.sync_end_time = datetime.datetime.now() 

1799 

1800 # Close the cycle on the webhooks. Failed downloads 

1801 # counted in the stats make this a failure even though 

1802 # the cycle itself ran to completion -- a monitor that 

1803 # reported success here would stay green while the 

1804 # library silently fell behind. So does a cycle that 

1805 # synced nothing at all. The statistics ride along, so a 

1806 # POST receiver sees them without app.notifications. 

1807 has_errors = summary.has_errors() 

1808 nothing_reason = _cycle_nothing_synced_reason( 

1809 config, 

1810 drive_stats, 

1811 photos_stats, 

1812 ) 

1813 # Every sync_failed names a reason, including this one: a 

1814 # receiver should never have to infer why from the 

1815 # statistics. (Only Photos counts failed downloads, so 

1816 # has_errors never means a Drive failure today.) 

1817 reason = nothing_reason or ("download_errors" if has_errors else None) 

1818 cycle_data = notify.summary_event_data(summary) 

1819 if reason: 

1820 cycle_data["reason"] = reason 

1821 notify.send_cycle_event( 

1822 config=config, 

1823 boundary="failure" if reason else "success", 

1824 message=_cycle_end_message(has_errors, nothing_reason), 

1825 data=cycle_data, 

1826 ) 

1827 

1828 # Persist per-service last-sync state for the web 

1829 # dashboard. Best-effort — if the JSON write fails 

1830 # the sync itself is unaffected. 

1831 try: 

1832 from src import web_signals as _ws 

1833 

1834 if drive_stats is not None: 

1835 _ws.record_sync_completion( 

1836 service="drive", 

1837 files_downloaded=drive_stats.files_downloaded, 

1838 files_skipped=drive_stats.files_skipped, 

1839 files_removed=drive_stats.files_removed, 

1840 errors=len(drive_stats.errors), 

1841 duration_seconds=drive_stats.duration_seconds, 

1842 ) 

1843 if photos_stats is not None: 

1844 _ws.record_sync_completion( 

1845 service="photos", 

1846 files_downloaded=photos_stats.photos_downloaded, 

1847 files_skipped=photos_stats.photos_skipped, 

1848 errors=len(photos_stats.errors), 

1849 duration_seconds=photos_stats.duration_seconds, 

1850 ) 

1851 except ( 

1852 ImportError 

1853 ): # pragma: no cover — best-effort fallback for builds without web_signals 

1854 pass 

1855 except Exception as e: 

1856 LOGGER.debug( 

1857 f"web_signals: record_sync_completion raised: {e!s}", 

1858 ) 

1859 

1860 # Send usage statistics (anonymized summary data) 

1861 try: 

1862 _send_usage_statistics(config, summary) 

1863 except Exception as e: 

1864 LOGGER.debug(f"Failed to send usage statistics: {e!s}") 

1865 

1866 # Send sync summary notification if configured 

1867 # Only send notification when both enabled services have synced in this cycle 

1868 # Gracefully handle notification failures to not break sync 

1869 has_drive_config = config and "drive" in config 

1870 has_photos_config = config and "photos" in config 

1871 

1872 should_send_notification = False 

1873 if has_drive_config and has_photos_config: 

1874 # Both services configured - send notification only when both have synced 

1875 should_send_notification = ( 

1876 drive_stats is not None and photos_stats is not None 

1877 ) 

1878 elif has_drive_config and not has_photos_config: 

1879 # Only drive configured - send when drive synced 

1880 should_send_notification = drive_stats is not None 

1881 elif has_photos_config and not has_drive_config: 

1882 # Only photos configured - send when photos synced 

1883 should_send_notification = photos_stats is not None 

1884 

1885 if should_send_notification: 

1886 try: 

1887 notify.send_sync_summary(config=config, summary=summary) 

1888 except Exception as e: 

1889 LOGGER.debug( 

1890 f"Failed to send sync summary notification: {e!s}", 

1891 ) 

1892 

1893 if not _check_services_configured(config): 

1894 LOGGER.warning( 

1895 "Nothing to sync. Please add drive: and/or photos: section in config.yaml file.", 

1896 ) 

1897 else: 

1898 _log_trust_revocation_hint(api) 

1899 if not _handle_2fa_required(config, username, sync_state, api): 

1900 break 

1901 continue 

1902 

1903 except exceptions.ICloudPyNoStoredPasswordAvailableException as e: 

1904 if not _handle_password_error(config, username, sync_state, e): 

1905 break 

1906 continue 

1907 except exceptions.ICloudPyFailedLoginException as e: 

1908 # icloudpy catches most sign-in errors -- a 409 or 401 with a 

1909 # reason, any 5xx -- and re-raises them as this, which 

1910 # subclasses ICloudPyException directly and so is not caught by 

1911 # the API-response clause below. It only arises while signing 

1912 # in, so it always takes the auth backoff. 

1913 if not _handle_auth_transport_error(config, username, sync_state, e): 

1914 break 

1915 continue 

1916 except exceptions.ICloudPyServiceNotActivatedException as e: 

1917 # A zone or service being unavailable says nothing about the 

1918 # sign-in whenever it surfaces, so it never earns the 

1919 # rate-limit backoff. Listed ahead of the broader catch 

1920 # below because it subclasses it. 

1921 if not _handle_sync_error( 

1922 config, 

1923 e, 

1924 drive_sync_interval, 

1925 photos_sync_interval, 

1926 ): 

1927 break 

1928 continue 

1929 except ( 

1930 exceptions.ICloudPyAPIResponseException, 

1931 requests.exceptions.RequestException, 

1932 ) as e: 

1933 # Any other failure raised after the sign-in succeeded is a 

1934 # service problem, not an auth problem -- and must not earn 

1935 # the backoff meant for "you are trying too often" either. 

1936 if authenticated: 

1937 if not _handle_sync_error( 

1938 config, 

1939 e, 

1940 drive_sync_interval, 

1941 photos_sync_interval, 

1942 ): 

1943 break 

1944 continue 

1945 # Apple refuses sign-in for reasons other than "2FA needed": 

1946 # 409 when it is throttling the account, 5xx when it is 

1947 # having a bad day, plus ordinary network faults. None of 

1948 # these are fatal, but letting them escape kills the process 

1949 # -- and with `restart: unless-stopped` that becomes a crash 

1950 # loop that re-authenticates every few seconds, which is the 

1951 # fastest possible way to deepen a throttle. 

1952 if not _handle_auth_transport_error(config, username, sync_state, e): 

1953 break 

1954 continue 

1955 

1956 sleep_for = _calculate_next_sync_schedule(config, sync_state) 

1957 _log_next_sync_time(sleep_for) 

1958 

1959 if _should_exit_oneshot_mode(config): 

1960 LOGGER.info( 

1961 "All configured sync intervals are negative, exiting oneshot mode...", 

1962 ) 

1963 break 

1964 

1965 # Interruptible sleep -- poll the web-signal force-sync sentinels 

1966 # every few seconds so the "Sync now" button stays responsive even 

1967 # mid-long-interval. Without this, a user tap during a multi-hour 

1968 # drive sleep would wait the full remaining duration. 

1969 _interruptible_sleep(sleep_for) 

1970 

1971 

1972def _interruptible_sleep(total_seconds: int) -> None: 

1973 """Sleep up to ``total_seconds`` in short chunks, returning early 

1974 when ``web_signals.pending_force_syncs()`` reports any sentinel. 

1975 

1976 The ``import src.web_signals`` is best-effort so a vanilla mandarons 

1977 build without the web-UI module still runs (it falls back to a 

1978 single ``sleep(total_seconds)``). 

1979 """ 

1980 _CHUNK = 2 # seconds — tradeoff: shorter = more responsive, more wakeups 

1981 try: 

1982 from src import web_signals as _ws 

1983 except ImportError: # pragma: no cover — vanilla-mandarons fallback 

1984 sleep(total_seconds) 

1985 return 

1986 

1987 # Short intervals (<= one chunk) sleep in a single call so the 

1988 # existing tests that count sleep invocations still match. The 

1989 # chunking only matters for long intervals where the user might 

1990 # tap "Sync now" mid-sleep -- those become multiple short sleeps 

1991 # with a sentinel poll between each. 

1992 if total_seconds <= _CHUNK: 

1993 sleep(total_seconds) 

1994 return 

1995 

1996 remaining = total_seconds 

1997 while remaining > 0: 

1998 chunk = min(_CHUNK, remaining) 

1999 sleep(chunk) 

2000 remaining -= chunk 

2001 if _ws.pending_force_syncs(): 

2002 return