Coverage for src/photo_download_manager.py: 100%

169 statements  

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

1"""Photo download task management module. 

2 

3This module contains utilities for managing photo download tasks 

4and parallel execution during photo synchronization. 

5""" 

6 

7___author___ = "Mandar Patil <mandarons@pm.me>" 

8 

9import os 

10from concurrent.futures import ThreadPoolExecutor, as_completed 

11from threading import Lock 

12 

13from src import DEFAULT_REQUEST_TIMEOUT_SEC, config_parser, get_logger 

14from src.download_report import get_download_report 

15from src.hardlink_registry import HardlinkRegistry 

16from src.photo_file_utils import create_hardlink, download_photo_from_server 

17from src.photo_path_utils import ( 

18 _LIVE_VIDEO_SIZES, 

19 create_folder_path_if_needed, 

20 generate_photo_filename_with_metadata, 

21 get_default_filename_format, 

22 get_file_format, 

23 normalize_file_path, 

24 photo_has_edit, 

25 rename_legacy_file_if_exists, 

26 version_record_id, 

27) 

28 

29LOGGER = get_logger() 

30 

31# Thread-safe lock for file set operations 

32files_lock = Lock() 

33 

34# ``photos.filters.fallback_to_original``: download ``original`` when an 

35# asset has no copy of a requested size. ``sync_photos`` sets this once per 

36# run from the parsed filters. 

37_FALLBACK_TO_ORIGINAL = False 

38 

39 

40def set_fallback_to_original(value: bool) -> None: 

41 """Set whether an absent requested size falls back to ``original``.""" 

42 global _FALLBACK_TO_ORIGINAL 

43 _FALLBACK_TO_ORIGINAL = bool(value) 

44 

45 

46def _size_present(photo, file_size: str, versions: dict) -> bool: 

47 """Whether ``file_size`` can be downloaded as itself. 

48 

49 A ``full`` that only the master record carries is Apple's display 

50 rendition for a format iCloud does not render natively, not an edit (see 

51 ``photo_path_utils.photo_has_edit``), so it counts as absent here too. 

52 """ 

53 if file_size not in versions: 

54 return False 

55 return file_size != "full" or photo_has_edit(photo) 

56 

57 

58def would_fall_back_to_original(photo, file_size: str) -> bool: 

59 """Whether ``collect_download_task`` would download ``original`` instead. 

60 

61 The album orchestrator uses this to claim the substitution once per photo: 

62 with two requested sizes a photo lacks (e.g. ``[adjusted, alternative]``), 

63 both would otherwise resolve to the same ``original`` path and race. 

64 """ 

65 if not _FALLBACK_TO_ORIGINAL: 

66 return False 

67 if file_size == "original" or file_size.startswith("live_video_"): 

68 return False 

69 versions = photo.versions 

70 return not _size_present(photo, file_size, versions) and "original" in versions 

71 

72 

73class DownloadTaskInfo: 

74 """Information about a photo download task.""" 

75 

76 def __init__( 

77 self, 

78 photo, 

79 file_size: str, 

80 photo_path: str, 

81 hardlink_source: str | None = None, 

82 hardlink_registry: HardlinkRegistry | None = None, 

83 timeout: int = DEFAULT_REQUEST_TIMEOUT_SEC, 

84 ): 

85 """Initialize download task info. 

86 

87 Args: 

88 photo: Photo object from iCloudPy 

89 file_size: File size variant (original, medium, thumb, etc.) 

90 photo_path: Target path for photo download 

91 hardlink_source: Path to existing file for hardlink creation 

92 hardlink_registry: Registry for tracking downloaded files 

93 timeout: HTTP read timeout for the download, in seconds 

94 """ 

95 self.photo = photo 

96 self.file_size = file_size 

97 self.photo_path = photo_path 

98 self.hardlink_source = hardlink_source 

99 self.hardlink_registry = hardlink_registry 

100 self.timeout = timeout 

101 # Filled by download_photo_from_server when the transfer is unusable, 

102 # and reported once the task finishes. 

103 self.failure: dict = {} 

104 # Paths the run owns, granted only after a verified write (or hardlink). 

105 self.files: set[str] | None = None 

106 

107 

108def get_max_threads_for_download(config) -> int: 

109 """Get maximum number of threads for parallel downloads. 

110 

111 Args: 

112 config: Configuration dictionary 

113 

114 Returns: 

115 Maximum number of threads to use for downloads 

116 """ 

117 return config_parser.get_app_max_threads(config) 

118 

119 

120def _move_master_named_edit(photo, file_size: str, folder: str, path: str) -> None: 

121 """Move an edit left under its old, master-record name onto ``path``. 

122 

123 An edit was named after the master record until each copy's edit got 

124 its own record's ID (see ``version_record_id``); moving the file saves 

125 downloading it again. Only when its size says it is this version: 

126 copies of one photo shared that name, so the file there is whichever 

127 copy's edit was written last. 

128 """ 

129 if version_record_id(photo, file_size) == photo.id or os.path.isfile(path): 

130 return 

131 master_named = normalize_file_path( 

132 os.path.join(folder, generate_photo_filename_with_metadata(photo, file_size, record_id=photo.id)), 

133 ) 

134 expected_size = (photo.versions.get(file_size) or {}).get("size") 

135 try: 

136 master_named_size = os.path.getsize(master_named) if os.path.isfile(master_named) else None 

137 except OSError: # pragma: no cover - raced away between the two calls 

138 master_named_size = None 

139 if master_named != path and expected_size is not None and master_named_size == expected_size: 

140 rename_legacy_file_if_exists(master_named, path) 

141 

142 

143def generate_photo_path(photo, file_size: str, destination_path: str, folder_format: str | None) -> str: 

144 """Generate full file path for photo with legacy file renaming. 

145 

146 This function combines path generation, folder creation, and legacy 

147 file renaming into a single operation to maintain backward compatibility. 

148 

149 Args: 

150 photo: Photo object from iCloudPy 

151 file_size: File size variant (original, medium, thumb, etc.) 

152 destination_path: Base destination path 

153 folder_format: strftime format string for folder creation 

154 

155 Returns: 

156 Normalized full path where photo should be saved 

157 """ 

158 # Generate filename with metadata 

159 filename_with_metadata = generate_photo_filename_with_metadata(photo, file_size) 

160 

161 # Create folder path if needed 

162 final_destination = create_folder_path_if_needed( 

163 destination_path, folder_format, photo, 

164 ) 

165 

166 # Generate paths for legacy file format handling 

167 filename = photo.filename 

168 name, extension = filename.rsplit(".", 1) if "." in filename else [filename, ""] 

169 

170 # Legacy file paths that need to be renamed 

171 file_path = os.path.join(destination_path, filename) 

172 file_size_path = os.path.join( 

173 destination_path, 

174 (f"{'__'.join([name, file_size])}" if extension == "" else f"{'__'.join([name, file_size])}.{extension}"), 

175 ) 

176 

177 # Final path with normalization 

178 final_file_path = os.path.join(final_destination, filename_with_metadata) 

179 normalized_path = normalize_file_path(final_file_path) 

180 

181 # The path the still legitimately occupies under the active naming 

182 # scheme. Every legacy rename below moves a file onto *this* variant's 

183 # path, and os.rename replaces its target -- so a rename starting from 

184 # the still destroys the still and whatever stood at the target. Without 

185 # folder_format the destination and the photo's folder are the same 

186 # directory, which makes the flat "legacy" paths below identical to the 

187 # still's current one. 

188 still_path = normalize_file_path( 

189 os.path.join( 

190 final_destination, 

191 generate_photo_filename_with_metadata(photo, "original"), 

192 ), 

193 ) 

194 _moves_the_still = file_size in _LIVE_VIDEO_SIZES 

195 

196 # Rename legacy files if they exist 

197 if not (_moves_the_still and file_path == still_path): 

198 rename_legacy_file_if_exists(file_path, normalized_path) 

199 if not (_moves_the_still and file_size_path == still_path): 

200 rename_legacy_file_if_exists(file_size_path, normalized_path) 

201 

202 # Self-heal the earlier .HEIC mislabeling of Live Photo videos: an older 

203 # version wrote the paired video with the still's extension. Rename that 

204 # file to the corrected path instead of re-downloading it (which would also 

205 # leave the broken duplicate behind). 

206 if file_size in _LIVE_VIDEO_SIZES and extension: 

207 root, _ = os.path.splitext(filename_with_metadata) 

208 legacy_mislabeled = normalize_file_path( 

209 os.path.join(final_destination, f"{root}.{extension}"), 

210 ) 

211 # Under a naming scheme that keeps the photo's own filename, ``root`` 

212 # is the still's stem, so the candidate above IS the still's correct 

213 # path -- renaming it would move the still onto the video's path and, 

214 # because os.rename replaces its target, destroy the video too. The 

215 # mislabeled file this heals only exists under a scheme that encodes 

216 # the variant in the name, where the two paths cannot coincide. 

217 # Confirm the candidate really is the paired video before moving it. 

218 # os.rename replaces its target, so an unverified rename destroys two 

219 # files at once and logs nothing. CloudKit already reports how long 

220 # the video should be, so this costs a stat and no extra I/O: a file 

221 # of some other length is not the video, whatever it is named. 

222 expected_size = (photo.versions.get(file_size) or {}).get("size") 

223 try: 

224 candidate_size = ( 

225 os.path.getsize(legacy_mislabeled) 

226 if os.path.isfile(legacy_mislabeled) 

227 else None 

228 ) 

229 except OSError: # pragma: no cover - raced away between the two calls 

230 candidate_size = None 

231 if ( 

232 legacy_mislabeled not in (normalized_path, still_path) 

233 and expected_size is not None 

234 and candidate_size == expected_size 

235 ): 

236 rename_legacy_file_if_exists(legacy_mislabeled, normalized_path) 

237 

238 _move_master_named_edit(photo, file_size, final_destination, normalized_path) 

239 

240 # Handle existing file with different normalization 

241 if os.path.isfile(final_file_path) and final_file_path != normalized_path: 

242 rename_legacy_file_if_exists(final_file_path, normalized_path) 

243 

244 return normalized_path 

245 

246 

247def collect_download_task( 

248 photo, 

249 file_size: str, 

250 destination_path: str, 

251 files: set[str] | None, 

252 folder_format: str | None, 

253 hardlink_registry: HardlinkRegistry | None, 

254 claimed_paths: set[str] | None = None, 

255) -> DownloadTaskInfo | None: 

256 """Collect photo info for parallel download without immediately downloading. 

257 

258 Args: 

259 photo: Photo object from iCloudPy 

260 file_size: File size variant (original, medium, thumb, etc.) 

261 destination_path: Base destination path 

262 files: Set of paths the run owns; a task's path is added there only 

263 after its write succeeds (or when an existing file is verified) 

264 folder_format: strftime format string for folder creation 

265 hardlink_registry: Registry for tracking downloaded files 

266 claimed_paths: Set of paths already queued earlier in this album pass. 

267 Used only to route an in-flight collision to the suffix name; the 

268 path is not treated as owned until the transfer verifies. 

269 

270 Returns: 

271 DownloadTaskInfo if photo needs to be processed, None if skipped 

272 """ 

273 # Check if file size exists on server. With ``fallback_to_original`` on, an 

274 # absent size downloads the original instead of skipping -- that is what 

275 # makes ``[adjusted]`` mean "the edit, or the untouched original if the 

276 # photo was never edited". 

277 # 

278 # ``full`` only counts as present when the asset record carries the edit 

279 # (see ``photo_has_edit``): a master-carried ``full`` is Apple's display 

280 # rendition for a format it does not render natively, and treating it as 

281 # an edit would hide a PNG/RAW original behind ``.original.bak``. 

282 # 

283 # ``live_video_*`` never falls back: those versions are QuickTime movies, 

284 # and writing the still image's bytes under a ``.mov`` name would be 

285 # corrupt data rather than a substitute. 

286 versions = photo.versions 

287 if not _size_present(photo, file_size, versions): 

288 if would_fall_back_to_original(photo, file_size): 

289 LOGGER.debug( 

290 f"File size {file_size} not found on server for {photo.filename}. " 

291 "Downloading original instead.", 

292 ) 

293 file_size = "original" 

294 else: 

295 photo_path = generate_photo_path(photo, file_size, destination_path, folder_format) 

296 # A missing live_video_* version just means this isn't a Live Photo -- 

297 # expected for most assets, so log at DEBUG to avoid warning-spam when 

298 # live_video_original is in file_sizes. Other sizes warn as before. 

299 msg = f"File size {file_size} not found on server. Skipping the photo {photo_path} ..." 

300 if file_size.startswith("live_video_"): 

301 LOGGER.debug(msg) 

302 else: 

303 LOGGER.warning(msg) 

304 return None 

305 

306 # Generate photo path 

307 photo_path = generate_photo_path(photo, file_size, destination_path, folder_format) 

308 

309 # Check if photo already exists with correct size 

310 from src.photo_file_utils import check_photo_exists 

311 

312 if check_photo_exists(photo, file_size, photo_path): 

313 if files is not None: 

314 with files_lock: 

315 files.add(photo_path) 

316 return None 

317 

318 # Filename-collision fallback (``simple`` mode only): a plain 

319 # ``IMG_1234.HEIC`` path may already be claimed by a DIFFERENT iCloud 

320 # photo that happens to share the human filename. Two collision sources: 

321 # 

322 # 1. On-disk collision: ``check_photo_exists`` returned False but the 

323 # path is occupied -- size mismatch with a photo from a prior sync. 

324 # 2. In-flight collision: an earlier call in this same album pass 

325 # already queued this plain path. Without this check the later 

326 # parallel download silently overwrites the earlier one and we lose 

327 # data. ``claimed_paths`` is separate from ``files``: a queued path is 

328 # not owned until its transfer verifies, so a failed download cannot 

329 # shelter a file that was never written from obsolete cleanup. 

330 # Collection runs sequentially, so a plain membership test is enough. 

331 # 

332 # In either case we route this photo to the metadata-suffix filename so 

333 # both files coexist and both round-trip stably on future syncs. We use 

334 # the ``get_default_filename_format()`` accessor (rather than importing 

335 # the module-level constant) so ``set_default_filename_format`` updates 

336 # are observed live on every call. 

337 # Non-unique naming (simple mode, or a photos.file_format template that may 

338 # omit a unique component) can collide; the metadata format cannot. 

339 is_non_unique = get_default_filename_format() == "simple" or get_file_format() is not None 

340 in_flight_collision = False 

341 if is_non_unique and claimed_paths is not None: 

342 in_flight_collision = photo_path in claimed_paths 

343 if is_non_unique and (os.path.isfile(photo_path) or in_flight_collision): 

344 # Protect the file we are stepping around. This branch exists to 

345 # "preserve both photos", but obsolete-file cleanup deletes anything 

346 # absent from ``files`` -- so without this the run writes the suffix 

347 # copy and then deletes the very file it just refused to overwrite. 

348 # On a library with many repeated filenames that is not a rare edge 

349 # case: it deletes a large share of the library every sync, and the 

350 # next sync re-downloads it, because freeing the plain path changes 

351 # the collision outcome. Only an on-disk collision needs this; an 

352 # in-flight one means this run already claimed the path. 

353 if files is not None and os.path.isfile(photo_path): 

354 with files_lock: 

355 files.add(photo_path) 

356 suffix_folder = create_folder_path_if_needed( 

357 destination_path, folder_format, photo, 

358 ) 

359 suffix_basename = generate_photo_filename_with_metadata( 

360 photo, file_size, "metadata", 

361 ) 

362 photo_path = normalize_file_path(os.path.join(suffix_folder, suffix_basename)) 

363 LOGGER.info( 

364 f"Filename collision for {photo.filename} (id={photo.id}); " 

365 f"using suffix path {photo_path} to preserve both photos.", 

366 ) 

367 if check_photo_exists(photo, file_size, photo_path): 

368 if files is not None: 

369 with files_lock: 

370 files.add(photo_path) 

371 return None 

372 

373 if claimed_paths is not None: 

374 claimed_paths.add(photo_path) 

375 

376 # Check for existing hardlink source 

377 hardlink_source = None 

378 if hardlink_registry is not None: 

379 hardlink_source = hardlink_registry.get_existing_path(version_record_id(photo, file_size), file_size) 

380 

381 task = DownloadTaskInfo( 

382 photo=photo, 

383 file_size=file_size, 

384 photo_path=photo_path, 

385 hardlink_source=hardlink_source, 

386 hardlink_registry=hardlink_registry, 

387 ) 

388 # Bound here, granted only when execute_download_task's write verifies. 

389 task.files = files 

390 return task 

391 

392 

393def _claim_owned(task_info: DownloadTaskInfo) -> None: 

394 """Record the task's path as owned once its write (or hardlink) succeeded.""" 

395 if task_info.files is not None: 

396 with files_lock: 

397 task_info.files.add(task_info.photo_path) 

398 

399 

400def execute_download_task(task_info: DownloadTaskInfo) -> bool: 

401 """Download a single photo or create hardlink as part of parallel execution. 

402 

403 Args: 

404 task_info: Download task information 

405 

406 Returns: 

407 True if task completed successfully, False otherwise 

408 """ 

409 LOGGER.debug(f"[Thread] Starting processing of {task_info.photo_path}") 

410 

411 try: 

412 # Try hardlink first if source exists 

413 if task_info.hardlink_source: 

414 if create_hardlink(task_info.hardlink_source, task_info.photo_path): 

415 _claim_owned(task_info) 

416 LOGGER.debug(f"[Thread] Created hardlink for {task_info.photo_path}") 

417 return True 

418 else: 

419 # Fallback to download if hard link creation fails 

420 LOGGER.warning( 

421 f"Hard link creation failed, downloading {task_info.photo_path} instead", 

422 ) 

423 

424 # Download the photo 

425 result = download_photo_from_server( 

426 task_info.photo, 

427 task_info.file_size, 

428 task_info.photo_path, 

429 timeout=task_info.timeout, 

430 failure=task_info.failure, 

431 ) 

432 if result: 

433 _claim_owned(task_info) 

434 elif task_info.failure: 

435 get_download_report().record(task_info.failure) 

436 

437 if result and task_info.hardlink_registry is not None: 

438 # Register for future hard links if enabled 

439 task_info.hardlink_registry.register_photo_path( 

440 version_record_id(task_info.photo, task_info.file_size), 

441 task_info.file_size, 

442 task_info.photo_path, 

443 ) 

444 LOGGER.debug(f"[Thread] Completed download of {task_info.photo_path}") 

445 

446 return result 

447 

448 except Exception as e: 

449 LOGGER.error(f"[Thread] Failed to process {task_info.photo_path}: {e!s}") 

450 return False 

451 

452 

453def execute_parallel_downloads( 

454 download_tasks: list[DownloadTaskInfo], config, 

455) -> tuple[int, int]: 

456 """Execute download tasks in parallel using thread pool. 

457 

458 Args: 

459 download_tasks: List of download tasks to execute 

460 config: Configuration dictionary for thread settings 

461 

462 Returns: 

463 Tuple of (successful_downloads, failed_downloads) 

464 """ 

465 if not download_tasks: 

466 return 0, 0 

467 

468 max_threads = get_max_threads_for_download(config) 

469 

470 # Resolved once here rather than per task: without it a stalled CDN 

471 # connection blocks its worker thread for the life of the process. 

472 timeout = config_parser.get_photos_request_timeout(config) 

473 for task in download_tasks: 

474 task.timeout = timeout 

475 

476 # Count hardlink tasks vs download tasks for logging 

477 hardlink_tasks = sum(1 for task in download_tasks if task.hardlink_source) 

478 download_only_tasks = len(download_tasks) - hardlink_tasks 

479 

480 if hardlink_tasks > 0: 

481 LOGGER.info( 

482 f"Starting parallel processing with {max_threads} threads: " 

483 f"{hardlink_tasks} hard links, {download_only_tasks} downloads...", 

484 ) 

485 else: 

486 LOGGER.info( 

487 f"Starting parallel photo downloads with {max_threads} threads for {len(download_tasks)} photos...", 

488 ) 

489 

490 successful_downloads = 0 

491 failed_downloads = 0 

492 

493 with ThreadPoolExecutor(max_workers=max_threads) as executor: 

494 # Submit all download tasks 

495 future_to_task = { 

496 executor.submit(execute_download_task, task): task 

497 for task in download_tasks 

498 } 

499 

500 # Process completed downloads 

501 for future in as_completed(future_to_task): 

502 try: 

503 result = future.result() 

504 if result: 

505 successful_downloads += 1 

506 else: 

507 failed_downloads += 1 

508 except Exception as e: # noqa: PERF203 

509 LOGGER.error(f"Unexpected error during photo download: {e!s}") 

510 failed_downloads += 1 

511 

512 LOGGER.info( 

513 f"Photo processing complete: {successful_downloads} successful, {failed_downloads} failed", 

514 ) 

515 return successful_downloads, failed_downloads