Coverage for src/__init__.py: 100%
129 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
1"""Root module."""
3__author__ = "Mandar Patil (mandarons@pm.me)"
5import logging
6import os
7import sys
8import warnings
9from logging.handlers import RotatingFileHandler
11from ruamel.yaml import YAML
13DEFAULT_ROOT_DESTINATION = "./icloud"
14DEFAULT_DRIVE_DESTINATION = "drive"
15DEFAULT_PHOTOS_DESTINATION = "photos"
16DEFAULT_RETRY_LOGIN_INTERVAL_SEC = 600 # 10 minutes
17DEFAULT_SYNC_INTERVAL_SEC = 1800 # 30 minutes
18DEFAULT_REQUEST_TIMEOUT_SEC = 30 # 30 seconds
19# Share of a destination that obsolete-cleanup may delete in one run before
20# it refuses and reports instead. A sync does not normally make a quarter of
21# a library obsolete; when it appears to, a tracking bug is likelier than a
22# real mass deletion. 0 disables the limit.
23DEFAULT_OBSOLETE_DELETE_LIMIT_PERCENT = 25
24DEFAULT_ENUMERATION_CHUNK_SIZE = 1000 # photos buffered per streaming chunk
25# Oldest a buffered photo download may get before the buffer is drained
26# early. Download URLs expire ~30-40 minutes after the listing that returned
27# them, and on a mostly backed-up library the few photos to fetch trickle in
28# across the whole walk. This keeps their wait short; anything that still
29# expires is recovered by the expired-URL refresh.
30BUFFERED_DOWNLOAD_MAX_AGE_SEC = 600 # 10 minutes
31DEFAULT_CONFIG_FILE_NAME = "config.yaml"
32ENV_ICLOUD_PASSWORD_KEY = "ENV_ICLOUD_PASSWORD"
33ENV_CONFIG_FILE_PATH_KEY = "ENV_CONFIG_FILE_PATH"
34DEFAULT_LOGGER_LEVEL = "info"
35DEFAULT_LOG_FILE_NAME = "icloud.log"
36# Rotation bounds for the file handler. A busy library logs one line per
37# file *considered* each cycle, so an unbounded handler grows without
38# limit -- multi-GB logs on large accounts. 50 MB x 3 backups keeps a
39# useful window at a bounded 200 MB worst case.
40DEFAULT_LOG_MAX_BYTES = 50 * 1024 * 1024
41DEFAULT_LOG_BACKUP_COUNT = 3
42DEFAULT_CONFIG_FILE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), DEFAULT_CONFIG_FILE_NAME)
43# Operator-overridable via ICLOUD_DOCKER_CONFIG_DIR. Default ``/config`` is the
44# in-container mount point users bind their config volume to. The override
45# lets the test suite run on hosts where ``/config`` isn't writable (macOS,
46# sandboxes).
47_CONFIG_DIR = os.environ.get("ICLOUD_DOCKER_CONFIG_DIR", "/config")
48DEFAULT_COOKIE_DIRECTORY = os.path.join(_CONFIG_DIR, "session_data")
49# Apple's China-region endpoints. A China Apple ID must sign in against these
50# or every request fails with ``KeyError: 'webservices'``. They live here, in
51# one place, because both the sync loop (``src/sync.py``) and the Web UI
52# (``src/web.py``) authenticate the same account: if only one of them were
53# updated when Apple moves an endpoint, sign-in would succeed while sync
54# failed, or the reverse.
55CHINA_HOME_ENDPOINT = "https://www.icloud.com.cn"
56CHINA_SETUP_ENDPOINT = "https://setup.icloud.com.cn/setup/ws/1"
58warnings.filterwarnings("ignore", category=DeprecationWarning)
61def read_config(config_path=DEFAULT_CONFIG_FILE_PATH):
62 """Read config file."""
63 if not (config_path and os.path.exists(config_path)):
64 print(f"Config file not found at {config_path}.")
65 return None
66 with open(file=config_path, encoding="utf-8") as config_file:
67 config = YAML().load(config_file)
68 config["app"]["credentials"]["username"] = (
69 config["app"]["credentials"]["username"].strip() if config["app"]["credentials"]["username"] is not None else ""
70 )
71 return config
74def get_logger_config(config):
75 """Get logger config."""
76 logger_config = {}
77 # ``read_config`` returns None when config.yaml is missing, and a partial
78 # file may have no ``app`` section. Both reached ``config["app"]`` and
79 # raised -- from module scope, so the container could not start at all.
80 # Shape-check every level, not just presence: a parseable but wrong YAML
81 # (``app: 123``, ``logger: info``) otherwise raises TypeError here at
82 # import time -- the same restart loop this guard exists to prevent.
83 app = config.get("app") if isinstance(config, dict) else None
84 config_app_logger = app.get("logger") if isinstance(app, dict) else None
85 if not isinstance(config_app_logger, dict):
86 return None
87 logger_config["level"] = (
88 config_app_logger["level"].strip().lower() if "level" in config_app_logger else DEFAULT_LOGGER_LEVEL
89 )
90 logger_config["filename"] = (
91 config_app_logger["filename"].strip().lower() if "filename" in config_app_logger else DEFAULT_LOG_FILE_NAME
92 )
93 logger_config["max_bytes"] = _int_setting(config_app_logger, "max_bytes", DEFAULT_LOG_MAX_BYTES)
94 logger_config["backup_count"] = _int_setting(config_app_logger, "backup_count", DEFAULT_LOG_BACKUP_COUNT)
95 return logger_config
98def _int_setting(section, key, default):
99 """Read an integer logger setting, falling back to ``default`` on junk.
101 This runs while logging is being configured -- at import, before any
102 handler exists -- so a bare ``int()`` on a typo like ``max_bytes: 50MB``
103 raised out of module import and, under ``restart: unless-stopped``,
104 became a restart loop that never said which key was wrong. Say so on
105 stdout (no logger yet) and carry on with the default.
106 """
107 value = section.get(key, default)
108 try:
109 return int(value)
110 except (TypeError, ValueError):
111 print(f"app.logger.{key} must be a whole number, got {value!r}; using {default}.")
112 return default
115def log_handler_exists(logger, handler_type, **kwargs):
116 """Check for existing log handler."""
117 for handler in logger.handlers:
118 if isinstance(handler, handler_type):
119 if handler_type is logging.FileHandler:
120 if handler.baseFilename.endswith(kwargs["filename"]):
121 return True
122 elif handler_type is logging.StreamHandler:
123 if handler.stream is kwargs["stream"]:
124 return True
125 return False
128class ColorfulConsoleFormatter(logging.Formatter):
129 """Console formatter for log messages."""
131 grey = "\x1b[38;21m"
132 blue = "\x1b[38;5;39m"
133 yellow = "\x1b[38;5;226m"
134 red = "\x1b[38;5;196m"
135 bold_red = "\x1b[31;1m"
136 reset = "\x1b[0m"
138 def __init__(self, fmt):
139 """Construct with defaults."""
140 super().__init__()
141 self.fmt = fmt
142 self.formats = {
143 logging.DEBUG: self.grey + self.fmt + self.reset,
144 logging.INFO: self.blue + self.fmt + self.reset,
145 logging.WARNING: self.yellow + self.fmt + self.reset,
146 logging.ERROR: self.red + self.fmt + self.reset,
147 logging.CRITICAL: self.bold_red + self.fmt + self.reset,
148 }
150 def format(self, record):
151 """Format the record."""
152 log_fmt = self.formats.get(record.levelno)
153 formatter = logging.Formatter(log_fmt)
154 return formatter.format(record)
157def configure_icloudpy_logging():
158 """Configure icloudpy logging to match app logging level."""
159 logger_config = get_logger_config(config=read_config(config_path=os.environ.get(ENV_CONFIG_FILE_PATH_KEY, DEFAULT_CONFIG_FILE_PATH)))
160 if logger_config:
161 level_name = logging.getLevelName(level=logger_config["level"].upper())
163 # Configure icloudpy loggers to use the same level and enable propagation
164 icloudpy_loggers = [
165 logging.getLogger("icloudpy"),
166 logging.getLogger("icloudpy.base"),
167 logging.getLogger("icloudpy.services"),
168 logging.getLogger("icloudpy.services.photos"),
169 ]
170 for icloudpy_logger in icloudpy_loggers:
171 icloudpy_logger.setLevel(level=level_name)
172 # Enable propagation so messages go to root logger handlers
173 icloudpy_logger.propagate = True
174 # Remove any existing handlers to avoid duplicates
175 icloudpy_logger.handlers.clear()
178def apply_default_request_timeout(session, timeout: int = DEFAULT_REQUEST_TIMEOUT_SEC):
179 """Bound every request ``session`` makes that does not carry its own timeout.
181 ``requests`` has no default timeout, and icloudpy's CloudKit listing
182 calls -- ``_zone_post``, the ``zones/list`` call and the album page
183 queries behind them -- pass none, so a half-open connection (an ISP
184 reconnect, a VPN flap) blocks the sync loop on a socket read that
185 never returns and no log line ever explains. icloudpy shares one
186 session across all of its services, so wrapping that session's
187 ``send`` -- the funnel every request ends at -- bounds the listing
188 calls from here, without a library change. A timeout a caller passes
189 itself (the download paths pass theirs) always wins; only a missing
190 or ``None`` timeout is filled in.
192 Wrapping ``send`` rather than ``request`` is deliberate:
193 ``ICloudPySession.request`` attributes each request's log line to
194 ``inspect.stack()[2]``, and a wrapper around ``request`` becomes that
195 frame, moving the line to ``requests.sessions.http``. Bounding ``send``
196 leaves ``session.request`` untouched, so icloudpy keeps logging under
197 the calling service's logger. ``Session.request`` always forwards to
198 ``self.send`` with the caller's timeout (``None`` when unset), so the
199 same fill-in applies.
201 Args:
202 session: The ``requests`` session to bound, or ``None``.
203 timeout: Timeout in seconds applied to unbounded requests.
205 Returns:
206 The session, wrapped in place, so callers can use it inline.
207 Wrapping is idempotent: an already-wrapped session is returned
208 unchanged, and ``None`` passes straight through.
209 """
210 if session is None:
211 return None
212 if getattr(session, "_has_default_request_timeout", False):
213 return session
214 original_send = session.send
216 def send_with_default_timeout(*args, **kwargs):
217 if kwargs.get("timeout") is None:
218 kwargs["timeout"] = timeout
219 return original_send(*args, **kwargs)
221 session.send = send_with_default_timeout
222 session._has_default_request_timeout = True # noqa: SLF001
223 return session
226def get_logger():
227 """Return logger."""
228 logger = logging.getLogger()
229 # This runs at import time, so anything raised here stops the container
230 # before it can report why -- and `restart: unless-stopped` turns that
231 # into a restart loop. A config too broken to parse is the sync loop's
232 # problem to report; here it just means default logging.
233 try:
234 config = read_config(config_path=os.environ.get(ENV_CONFIG_FILE_PATH_KEY, DEFAULT_CONFIG_FILE_PATH))
235 except Exception: # noqa: BLE001 -- import-time: never crash on a bad config
236 config = None
237 logger_config = get_logger_config(config=config)
238 if logger_config:
239 level_name = logging.getLevelName(level=logger_config["level"].upper())
240 logger.setLevel(level=level_name)
242 # Create handlers once and add them to root logger
243 file_handler = None
244 console_handler = None
246 if not log_handler_exists(
247 logger=logger,
248 handler_type=logging.FileHandler,
249 filename=logger_config["filename"],
250 ):
251 # Rotating rather than plain FileHandler: see
252 # DEFAULT_LOG_MAX_BYTES. max_bytes=0 disables rotation for
253 # operators who hand the file to an external logrotate.
254 file_handler = RotatingFileHandler(
255 logger_config["filename"],
256 maxBytes=logger_config["max_bytes"],
257 backupCount=logger_config["backup_count"],
258 )
259 file_handler.setFormatter(
260 logging.Formatter(
261 "%(asctime)s :: %(levelname)s :: %(name)s :: %(filename)s :: %(lineno)d :: %(message)s",
262 ),
263 )
264 logger.addHandler(file_handler)
266 if not log_handler_exists(logger=logger, handler_type=logging.StreamHandler, stream=sys.stdout):
267 console_handler = logging.StreamHandler(sys.stdout)
268 console_handler.setFormatter(
269 ColorfulConsoleFormatter(
270 "%(asctime)s :: %(levelname)s :: %(name)s :: %(filename)s :: %(lineno)d :: %(message)s",
271 ),
272 )
273 logger.addHandler(console_handler)
275 # Configure icloudpy loggers to use the same level and enable propagation
276 icloudpy_loggers = [
277 logging.getLogger("icloudpy"),
278 logging.getLogger("icloudpy.base"),
279 logging.getLogger("icloudpy.services"),
280 logging.getLogger("icloudpy.services.photos"),
281 ]
282 for icloudpy_logger in icloudpy_loggers:
283 icloudpy_logger.setLevel(level=level_name)
284 # Enable propagation so messages go to root logger handlers
285 icloudpy_logger.propagate = True
286 # Remove any existing handlers to avoid duplicates
287 icloudpy_logger.handlers.clear()
288 return logger
291LOGGER = get_logger()