-
Notifications
You must be signed in to change notification settings - Fork 554
/
base.py
1404 lines (1260 loc) · 49.6 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""Main script that uses Click to parse command-line arguments"""
from multiprocessing import freeze_support
import foundation
from icloudpd.mfa_provider import MFAProvider # fmt: skip
freeze_support() # fmt: skip # fixing tqdm on macos
import datetime
import itertools
import json
import logging
import os
import subprocess
import sys
import time
import typing
import urllib
from functools import partial
from logging import Logger
from threading import Thread
from typing import (
Callable,
Dict,
Iterable,
NoReturn,
Optional,
Sequence,
Tuple,
TypeVar,
cast,
)
import click
from pyicloud_ipd.base import PyiCloudService
from pyicloud_ipd.exceptions import PyiCloudAPIResponseException
from pyicloud_ipd.file_match import FileMatchPolicy
from pyicloud_ipd.raw_policy import RawTreatmentPolicy
from pyicloud_ipd.services.photos import PhotoAsset, PhotoLibrary, PhotosService
from pyicloud_ipd.utils import (
compose,
constant,
disambiguate_filenames,
get_password_from_keyring,
identity,
store_password_in_keyring,
)
from pyicloud_ipd.version_size import AssetVersionSize, LivePhotoVersionSize
from tqdm import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
from tzlocal import get_localzone
from icloudpd import constants, download, exif_datetime
from icloudpd.authentication import TwoStepAuthRequiredError, authenticator
from icloudpd.autodelete import autodelete_photos
from icloudpd.config import Config
from icloudpd.counter import Counter
from icloudpd.email_notifications import send_2sa_notification
from icloudpd.paths import clean_filename, local_download_path, remove_unicode_chars
from icloudpd.server import serve_app
from icloudpd.status import Status, StatusExchange
from icloudpd.string_helpers import truncate_middle
def build_filename_cleaner(
_ctx: click.Context, _param: click.Parameter, is_keep_unicode: bool
) -> Callable[[str], str]:
"""Map keep_unicode parameter for function for cleaning filenames"""
# redefining typed vars instead of using in ternary directly is a mypy hack
r: Callable[[str], str] = remove_unicode_chars
i: Callable[[str], str] = identity
return compose(
(r if not is_keep_unicode else i),
clean_filename,
)
def lp_filename_concatinator(filename: str) -> str:
name, ext = os.path.splitext(filename)
if not ext:
return filename
return name + ("_HEVC.MOV" if ext.lower().endswith(".heic") else ".MOV")
def lp_filename_original(filename: str) -> str:
name, ext = os.path.splitext(filename)
if not ext:
return filename
return name + ".MOV"
def build_lp_filename_generator(
_ctx: click.Context, _param: click.Parameter, lp_filename_policy: str
) -> Callable[[str], str]:
# redefining typed vars instead of using in ternary directly is a mypy hack
return lp_filename_original if lp_filename_policy == "original" else lp_filename_concatinator
def raw_policy_generator(
_ctx: click.Context, _param: click.Parameter, raw_policy: str
) -> RawTreatmentPolicy:
# redefining typed vars instead of using in ternary directly is a mypy hack
if raw_policy == "as-is":
return RawTreatmentPolicy.AS_IS
elif raw_policy == "original":
return RawTreatmentPolicy.AS_ORIGINAL
elif raw_policy == "alternative":
return RawTreatmentPolicy.AS_ALTERNATIVE
else:
raise ValueError(f"policy was provided with unsupported value of '{raw_policy}'")
def size_generator(
_ctx: click.Context, _param: click.Parameter, sizes: Sequence[str]
) -> Sequence[AssetVersionSize]:
def _map(size: str) -> AssetVersionSize:
if size == "original":
return AssetVersionSize.ORIGINAL
elif size == "adjusted":
return AssetVersionSize.ADJUSTED
elif size == "alternative":
return AssetVersionSize.ALTERNATIVE
elif size == "medium":
return AssetVersionSize.MEDIUM
elif size == "thumb":
return AssetVersionSize.THUMB
else:
raise ValueError(f"size was provided with unsupported value of '{size}'")
return [_map(_s) for _s in sizes]
def mfa_provider_generator(
_ctx: click.Context, _param: click.Parameter, provider: str
) -> MFAProvider:
if provider == "console":
return MFAProvider.CONSOLE
elif provider == "webui":
return MFAProvider.WEBUI
else:
raise ValueError(f"mfa provider has unsupported value of '{provider}'")
def ask_password_in_console(_user: str) -> Optional[str]:
return typing.cast(Optional[str], click.prompt("iCloud Password", hide_input=True))
# return getpass.getpass(
# f'iCloud Password for {_user}:'
# )
def get_password_from_webui(
logger: Logger, status_exchange: StatusExchange
) -> Callable[[str], Optional[str]]:
def _intern(_user: str) -> Optional[str]:
"""Request two-factor authentication through Webui."""
if not status_exchange.replace_status(Status.NO_INPUT_NEEDED, Status.NEED_PASSWORD):
logger.error("Expected NO_INPUT_NEEDED, but got something else")
return None
# wait for input
while True:
status = status_exchange.get_status()
if status == Status.NEED_PASSWORD:
time.sleep(1)
else:
break
if status_exchange.replace_status(Status.SUPPLIED_PASSWORD, Status.CHECKING_PASSWORD):
password = status_exchange.get_payload()
if not password:
logger.error("Internal error: did not get password for SUPPLIED_PASSWORD status")
status_exchange.replace_status(
Status.CHECKING_PASSWORD, Status.NO_INPUT_NEEDED
) # TODO Error
return None
return password
return None # TODO
return _intern
def update_password_status_in_webui(status_exchange: StatusExchange) -> Callable[[str, str], None]:
def _intern(_u: str, _p: str) -> None:
# TODO we are not handling wrong passwords...
status_exchange.replace_status(Status.CHECKING_PASSWORD, Status.NO_INPUT_NEEDED)
return None
return _intern
# def get_click_param_by_name(_name: str, _params: List[Parameter]) -> Optional[Parameter]:
# _with_password = [_p for _p in _params if _name in _p.name]
# if len(_with_password) == 0:
# return None
# return _with_password[0]
def dummy_password_writter(_u: str, _p: str) -> None:
pass
def keyring_password_writter(logger: Logger) -> Callable[[str, str], None]:
def _intern(username: str, password: str) -> None:
try:
store_password_in_keyring(username, password)
except Exception:
logger.warning("Password was not saved to keyring")
return _intern
def password_provider_generator(
_ctx: click.Context, _param: click.Parameter, providers: Sequence[str]
) -> Dict[str, Tuple[Callable[[str], Optional[str]], Callable[[str, str], None]]]:
def _map(provider: str) -> Tuple[Callable[[str], Optional[str]], Callable[[str, str], None]]:
if provider == "webui":
return (ask_password_in_console, dummy_password_writter)
if provider == "console":
return (ask_password_in_console, dummy_password_writter)
elif provider == "keyring":
return (get_password_from_keyring, dummy_password_writter)
elif provider == "parameter":
# TODO get from parameter
# _param: Optional[Parameter] = get_click_param_by_name("password", _ctx.command.params)
# if _param:
# _password: str = _param.consume_value(_ctx, {})
# return constant(_password)
return (constant(None), dummy_password_writter)
else:
raise ValueError(f"password provider was given an unsupported value of '{provider}'")
return dict([(_s, _map(_s)) for _s in providers])
def lp_size_generator(
_ctx: click.Context, _param: click.Parameter, size: str
) -> LivePhotoVersionSize:
if size == "original":
return LivePhotoVersionSize.ORIGINAL
elif size == "medium":
return LivePhotoVersionSize.MEDIUM
elif size == "thumb":
return LivePhotoVersionSize.THUMB
else:
raise ValueError(f"size was provided with unsupported value of '{size}'")
def file_match_policy_generator(
_ctx: click.Context, _param: click.Parameter, policy: str
) -> FileMatchPolicy:
if policy == "name-size-dedup-with-suffix":
return FileMatchPolicy.NAME_SIZE_DEDUP_WITH_SUFFIX
elif policy == "name-id7":
return FileMatchPolicy.NAME_ID7
else:
raise ValueError(f"policy was provided with unsupported value of '{policy}'")
def locale_setter(_ctx: click.Context, _param: click.Parameter, use_os_locale: bool) -> bool:
# set locale
if use_os_locale:
from locale import LC_ALL, setlocale
setlocale(LC_ALL, "")
return use_os_locale
def report_version(ctx: click.Context, _param: click.Parameter, value: bool) -> bool:
if not value:
return value
vi = foundation.version_info_formatted()
click.echo(vi)
ctx.exit()
# Must import the constants object so that we can mock values in tests.
CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
@click.command(context_settings=CONTEXT_SETTINGS, options_metavar="<options>")
# @click.argument(
@click.option(
"-d",
"--directory",
help="Local directory that should be used for download",
type=click.Path(exists=True),
metavar="<directory>",
)
@click.option(
"-u",
"--username",
help="Your iCloud username or email address",
metavar="<username>",
prompt="iCloud username/email",
)
@click.option(
"-p",
"--password",
help="Your iCloud password " "(default: use PyiCloud keyring or prompt for password)",
metavar="<password>",
# is_eager=True,
)
@click.option(
"--auth-only",
help="Create/Update cookie and session tokens only.",
is_flag=True,
)
@click.option(
"--cookie-directory",
help="Directory to store cookies for authentication " "(default: ~/.pyicloud)",
metavar="</cookie/directory>",
default="~/.pyicloud",
)
@click.option(
"--size",
help="Image size to download. `medium` and `thumb` will always be added as suffixes to filenames, `adjusted` and `alternative` only if conflicting, `original` - never. If `adjusted` or `alternative` specified and is missing, then `original` is used.",
type=click.Choice(["original", "medium", "thumb", "adjusted", "alternative"]),
default=["original"],
multiple=True,
show_default=True,
callback=size_generator,
)
@click.option(
"--live-photo-size",
help="Live Photo video size to download",
type=click.Choice(["original", "medium", "thumb"]),
default="original",
show_default=True,
callback=lp_size_generator,
)
@click.option(
"--recent",
help="Number of recent photos to download (default: download all photos)",
type=click.IntRange(0),
)
@click.option(
"--until-found",
help="Download most recently added photos until we find x number of "
"previously downloaded consecutive photos (default: download all photos)",
type=click.IntRange(0),
)
@click.option(
"-a",
"--album",
help="Album to download (default: All Photos)",
metavar="<album>",
default="All Photos",
)
@click.option(
"-l",
"--list-albums",
help="Lists the available albums",
is_flag=True,
)
@click.option(
"--library",
help="Library to download (default: Personal Library)",
metavar="<library>",
default="PrimarySync",
)
@click.option(
"--list-libraries",
help="Lists the available libraries",
is_flag=True,
)
@click.option(
"--skip-videos",
help="Don't download any videos (default: Download all photos and videos)",
is_flag=True,
)
@click.option(
"--skip-live-photos",
help="Don't download any live photos (default: Download live photos)",
is_flag=True,
)
@click.option(
"--force-size",
help="Only download the requested size (`adjusted` and `alternate` will not be forced)"
+ "(default: download original if size is not available)",
is_flag=True,
)
@click.option(
"--auto-delete",
help='Scans the "Recently Deleted" folder and deletes any files found in there. '
+ "(If you restore the photo in iCloud, it will be downloaded again.)",
is_flag=True,
)
@click.option(
"--only-print-filenames",
help="Only prints the filenames of all files that will be downloaded "
"(not including files that are already downloaded.)"
+ "(Does not download or delete any files.)",
is_flag=True,
)
@click.option(
"--folder-structure",
help="Folder structure (default: {:%Y/%m/%d}). "
"If set to 'none' all photos will just be placed into the download directory",
metavar="<folder_structure>",
default="{:%Y/%m/%d}",
)
@click.option(
"--set-exif-datetime",
help="Write the DateTimeOriginal exif tag from file creation date, " + "if it doesn't exist.",
is_flag=True,
)
@click.option(
"--smtp-username",
help="Your SMTP username, for sending email notifications when "
"two-step authentication expires.",
metavar="<smtp_username>",
)
@click.option(
"--smtp-password",
help="Your SMTP password, for sending email notifications when "
"two-step authentication expires.",
metavar="<smtp_password>",
)
@click.option(
"--smtp-host",
help="Your SMTP server host. Defaults to: smtp.gmail.com",
metavar="<smtp_host>",
default="smtp.gmail.com",
)
@click.option(
"--smtp-port",
help="Your SMTP server port. Default: 587 (Gmail)",
metavar="<smtp_port>",
type=click.IntRange(0),
default=587,
)
@click.option(
"--smtp-no-tls",
help="Pass this flag to disable TLS for SMTP (TLS is required for Gmail)",
metavar="<smtp_no_tls>",
is_flag=True,
)
@click.option(
"--notification-email",
help="Email address where you would like to receive email notifications. "
"Default: SMTP username",
metavar="<notification_email>",
)
@click.option(
"--notification-email-from",
help="Email address from which you would like to receive email notifications. "
"Default: SMTP username or notification-email",
metavar="<notification_email_from>",
)
@click.option(
"--notification-script",
type=click.Path(),
help="Runs an external script when two factor authentication expires. "
"(path required: /path/to/my/script.sh)",
)
@click.option(
"--log-level",
help="Log level (default: debug)",
type=click.Choice(["debug", "info", "error"]),
default="debug",
)
@click.option(
"--no-progress-bar",
help="Disables the one-line progress bar and prints log messages on separate lines "
"(Progress bar is disabled by default if there is no tty attached)",
is_flag=True,
)
@click.option(
"--threads-num",
help="Number of cpu threads - deprecated & always 1. To be removed in future version",
type=click.IntRange(1),
default=1,
)
@click.option(
"--delete-after-download",
help="Delete the photo/video after download it."
+ ' The deleted items will be appear in the "Recently Deleted".'
+ " Therefore, should not combine with --auto-delete option.",
is_flag=True,
)
@click.option(
"--domain",
help="What iCloud root domain to use. Use 'cn' for mainland China (default: 'com')",
type=click.Choice(["com", "cn"]),
default="com",
)
@click.option(
"--watch-with-interval",
help="Run downloading in a infinite cycle, waiting specified seconds between runs",
type=click.IntRange(1),
)
@click.option(
"--dry-run",
help="Do not modify local system or iCloud",
is_flag=True,
default=False,
)
@click.option(
"--keep-unicode-in-filenames",
"filename_cleaner",
help="Keep unicode chars in file names or remove non all ascii chars",
type=bool,
default=False,
callback=build_filename_cleaner,
)
@click.option(
"--live-photo-mov-filename-policy",
"lp_filename_generator",
help="How to produce filenames for video portion of live photos: `suffix` will add _HEVC suffix and `original` will keep filename as it is.",
type=click.Choice(["suffix", "original"], case_sensitive=False),
default="suffix",
callback=build_lp_filename_generator,
)
@click.option(
"--align-raw",
"raw_policy",
help="For photo assets with raw and jpeg, treat raw always in the specified size: `original` (raw+jpeg), `alternative` (jpeg+raw), or unchanged (as-is). It matters when choosing sizes to download",
type=click.Choice(["as-is", "original", "alternative"], case_sensitive=False),
default="as-is",
show_default=True,
callback=raw_policy_generator,
)
@click.option(
"--password-provider",
"password_providers",
help="Specifies passwords provider to check in the specified order",
type=click.Choice(["console", "keyring", "parameter", "webui"], case_sensitive=False),
default=["parameter", "keyring", "console"],
show_default=True,
multiple=True,
callback=password_provider_generator,
)
@click.option(
"--file-match-policy",
"file_match_policy",
help="Policy to identify existing files and de-duplicate. `name-size-dedup-with-suffix` appends file size to deduplicate. `name-id7` adds asset id from iCloud to all file names and does not de-duplicate.",
type=click.Choice(["name-size-dedup-with-suffix", "name-id7"], case_sensitive=False),
default="name-size-dedup-with-suffix",
show_default=True,
callback=file_match_policy_generator,
)
@click.option(
"--mfa-provider",
help="Specified where to get MFA code from",
type=click.Choice(["console", "webui"], case_sensitive=False),
default="console",
show_default=True,
callback=mfa_provider_generator,
)
@click.option(
"--use-os-locale",
help="Use locale of the host OS to format dates",
is_flag=True,
default=False,
is_eager=True,
callback=locale_setter,
)
@click.option(
"--version",
help="Show the version, commit hash and timestamp",
is_flag=True,
expose_value=False,
is_eager=True,
callback=report_version,
)
def main(
directory: Optional[str],
username: str,
password: Optional[str],
auth_only: bool,
cookie_directory: str,
size: Sequence[AssetVersionSize],
live_photo_size: LivePhotoVersionSize,
recent: Optional[int],
until_found: Optional[int],
album: str,
list_albums: bool,
library: str,
list_libraries: bool,
skip_videos: bool,
skip_live_photos: bool,
force_size: bool,
auto_delete: bool,
only_print_filenames: bool,
folder_structure: str,
set_exif_datetime: bool,
smtp_username: Optional[str],
smtp_password: Optional[str],
smtp_host: str,
smtp_port: int,
smtp_no_tls: bool,
notification_email: Optional[str],
notification_email_from: Optional[str],
log_level: str,
no_progress_bar: bool,
notification_script: Optional[str],
threads_num: int,
delete_after_download: bool,
domain: str,
watch_with_interval: Optional[int],
dry_run: bool,
filename_cleaner: Callable[[str], str],
lp_filename_generator: Callable[[str], str],
raw_policy: RawTreatmentPolicy,
password_providers: Dict[
str, Tuple[Callable[[str], Optional[str]], Callable[[str, str], None]]
],
file_match_policy: FileMatchPolicy,
mfa_provider: MFAProvider,
use_os_locale: bool,
) -> NoReturn:
"""Download all iCloud photos to a local directory"""
logging.basicConfig(
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
stream=sys.stdout,
)
logger = logging.getLogger("icloudpd")
if only_print_filenames:
logger.disabled = True
else:
# Need to make sure disabled is reset to the correct value,
# because the logger instance is shared between tests.
logger.disabled = False
if log_level == "debug":
logger.setLevel(logging.DEBUG)
elif log_level == "info":
logger.setLevel(logging.INFO)
elif log_level == "error":
logger.setLevel(logging.ERROR)
with logging_redirect_tqdm():
# check required directory param only if not list albums
if not list_albums and not list_libraries and not directory and not auth_only:
print("--auth-only, --directory, --list-libraries or --list-albums are required")
sys.exit(2)
if auto_delete and delete_after_download:
print("--auto-delete and --delete-after-download are mutually exclusive")
sys.exit(2)
if watch_with_interval and (list_albums or only_print_filenames): # pragma: no cover
print(
"--watch_with_interval is not compatible with --list_albums, --only_print_filenames"
)
sys.exit(2)
# hacky way to use one param in another
if password and "parameter" in password_providers:
# replace
password_providers["parameter"] = (constant(password), lambda _r, _w: None)
if len(password_providers) == 0: # pragma: no cover
print("You need to specify at least one --password-provider")
sys.exit(2)
if "console" in password_providers and "webui" in password_providers:
print("Console and webui are not compatible in --password-provider")
sys.exit(2)
if "console" in password_providers and list(password_providers)[-1] != "console":
print("Console must be the last --password-provider")
sys.exit(2)
if "webui" in password_providers and list(password_providers)[-1] != "webui":
print("Webui must be the last --password-provider")
sys.exit(2)
if folder_structure != "none":
try:
folder_structure.format(datetime.datetime.now())
except: # noqa E722
print("Format specified in --folder-structure is incorrect")
sys.exit(2)
status_exchange = StatusExchange()
config = Config(
directory=directory,
username=username,
auth_only=auth_only,
cookie_directory=cookie_directory,
size=size,
live_photo_size=live_photo_size,
recent=recent,
until_found=until_found,
album=album,
list_albums=list_albums,
library=library,
list_libraries=list_libraries,
skip_videos=skip_videos,
skip_live_photos=skip_live_photos,
force_size=force_size,
auto_delete=auto_delete,
only_print_filenames=only_print_filenames,
folder_structure=folder_structure,
set_exif_datetime=set_exif_datetime,
smtp_username=smtp_username,
smtp_host=smtp_host,
smtp_port=smtp_port,
smtp_no_tls=smtp_no_tls,
notification_email=notification_email,
notification_email_from=notification_email_from,
log_level=log_level,
no_progress_bar=no_progress_bar,
notification_script=notification_script,
threads_num=threads_num,
delete_after_download=delete_after_download,
domain=domain,
watch_with_interval=watch_with_interval,
dry_run=dry_run,
raw_policy=raw_policy,
password_providers=password_providers,
file_match_policy=file_match_policy,
mfa_provider=mfa_provider,
use_os_locale=use_os_locale,
)
status_exchange.set_config(config)
# hacky way to use one param in another
if "webui" in password_providers:
# replace
password_providers["webui"] = (
get_password_from_webui(logger, status_exchange),
update_password_status_in_webui(status_exchange),
)
# hacky way to inject logger
if "keyring" in password_providers:
# replace
password_providers["keyring"] = (
get_password_from_keyring,
keyring_password_writter(logger),
)
# start web server
if mfa_provider == MFAProvider.WEBUI:
server_thread = Thread(target=serve_app, daemon=True, args=[logger, status_exchange])
server_thread.start()
result = core(
download_builder(
logger,
skip_videos,
folder_structure,
directory,
size,
force_size,
only_print_filenames,
set_exif_datetime,
skip_live_photos,
live_photo_size,
dry_run,
file_match_policy,
)
if directory is not None
else (lambda _s: lambda _c, _p: False),
directory,
username,
auth_only,
cookie_directory,
size,
recent,
until_found,
album,
list_albums,
library,
list_libraries,
skip_videos,
auto_delete,
only_print_filenames,
folder_structure,
smtp_username,
smtp_password,
smtp_host,
smtp_port,
smtp_no_tls,
notification_email,
notification_email_from,
no_progress_bar,
notification_script,
delete_after_download,
domain,
logger,
watch_with_interval,
dry_run,
filename_cleaner,
lp_filename_generator,
raw_policy,
file_match_policy,
password_providers,
mfa_provider,
status_exchange,
)
sys.exit(result)
def download_builder(
logger: logging.Logger,
skip_videos: bool,
folder_structure: str,
directory: str,
size: Sequence[AssetVersionSize],
force_size: bool,
only_print_filenames: bool,
set_exif_datetime: bool,
skip_live_photos: bool,
live_photo_size: LivePhotoVersionSize,
dry_run: bool,
file_match_policy: FileMatchPolicy,
) -> Callable[[PyiCloudService], Callable[[Counter, PhotoAsset], bool]]:
"""factory for downloader"""
def state_(icloud: PyiCloudService) -> Callable[[Counter, PhotoAsset], bool]:
def download_photo_(counter: Counter, photo: PhotoAsset) -> bool:
"""internal function for actually downloading the photos"""
if skip_videos and photo.item_type != "image":
logger.debug(
"Skipping %s, only downloading photos." + "(Item type was: %s)",
photo.filename,
photo.item_type,
)
return False
if photo.item_type not in ("image", "movie"):
logger.debug(
"Skipping %s, only downloading photos and videos. " + "(Item type was: %s)",
photo.filename,
photo.item_type,
)
return False
try:
created_date = photo.created.astimezone(get_localzone())
except (ValueError, OSError):
logger.error(
"Could not convert photo created date to local timezone (%s)", photo.created
)
created_date = photo.created
if folder_structure.lower() == "none":
date_path = ""
else:
try:
date_path = folder_structure.format(created_date)
except ValueError: # pragma: no cover
# This error only seems to happen in Python 2
logger.error("Photo created date was not valid (%s)", photo.created)
# e.g. ValueError: year=5 is before 1900
# (https://github.com/icloud-photos-downloader/icloud_photos_downloader/issues/122)
# Just use the Unix epoch
created_date = datetime.datetime.fromtimestamp(0)
date_path = folder_structure.format(created_date)
try:
versions = disambiguate_filenames(photo.versions, size)
except KeyError as ex:
print(f"KeyError: {ex} attribute was not found in the photo fields.")
with open(file="icloudpd-photo-error.json", mode="w", encoding="utf8") as outfile:
json.dump(
{
"master_record": photo._master_record,
"asset_record": photo._asset_record,
},
outfile,
)
print("icloudpd has saved the photo record to: " "./icloudpd-photo-error.json")
print(
"Please create a Gist with the contents of this file: "
"https://gist.github.com"
)
print(
"Then create an issue on GitHub: "
"https://github.com/icloud-photos-downloader/icloud_photos_downloader/issues"
)
print(
"Include a link to the Gist in your issue, so that we can "
"see what went wrong.\n"
)
return False
download_dir = os.path.normpath(os.path.join(directory, date_path))
success = False
for download_size in size:
if download_size not in versions and download_size != AssetVersionSize.ORIGINAL:
if force_size:
logger.error(
"%s size does not exist for %s. Skipping...",
download_size.value,
photo.filename,
)
return False
if AssetVersionSize.ORIGINAL in size:
continue # that should avoid double download for original
download_size = AssetVersionSize.ORIGINAL
version = versions[download_size]
filename = version.filename
download_path = local_download_path(filename, download_dir)
original_download_path = None
file_exists = os.path.isfile(download_path)
if not file_exists and download_size == AssetVersionSize.ORIGINAL:
# Deprecation - We used to download files like IMG_1234-original.jpg,
# so we need to check for these.
# Now we match the behavior of iCloud for Windows: IMG_1234.jpg
original_download_path = ("-original.").join(download_path.rsplit(".", 1))
file_exists = os.path.isfile(original_download_path)
if file_exists:
if file_match_policy == FileMatchPolicy.NAME_SIZE_DEDUP_WITH_SUFFIX:
# for later: this crashes if download-size medium is specified
file_size = os.stat(original_download_path or download_path).st_size
photo_size = version.size
if file_size != photo_size:
download_path = (f"-{photo_size}.").join(download_path.rsplit(".", 1))
logger.debug("%s deduplicated", truncate_middle(download_path, 96))
file_exists = os.path.isfile(download_path)
if file_exists:
counter.increment()
logger.debug("%s already exists", truncate_middle(download_path, 96))
if not file_exists:
counter.reset()
if only_print_filenames:
print(download_path)
else:
truncated_path = truncate_middle(download_path, 96)
logger.debug("Downloading %s...", truncated_path)
download_result = download.download_media(
logger, dry_run, icloud, photo, download_path, version, download_size
)
success = download_result
if download_result:
if (
not dry_run
and set_exif_datetime
and filename.lower().endswith((".jpg", ".jpeg"))
and not exif_datetime.get_photo_exif(logger, download_path)
):
# %Y:%m:%d looks wrong, but it's the correct format
date_str = created_date.strftime("%Y-%m-%d %H:%M:%S%z")
logger.debug(
"Setting EXIF timestamp for %s: %s", download_path, date_str
)
exif_datetime.set_photo_exif(
logger,
download_path,
created_date.strftime("%Y:%m:%d %H:%M:%S"),
)
if not dry_run:
download.set_utime(download_path, created_date)
logger.info("Downloaded %s", truncated_path)
# Also download the live photo if present
if not skip_live_photos:
lp_size = live_photo_size
if lp_size in photo.versions:
version = photo.versions[lp_size]
lp_filename = version.filename
# if live_photo_size != "original":
# # Add size to filename if not original
# lp_filename = lp_filename.replace(
# ".MOV", f"-{live_photo_size}.MOV"
# )
lp_download_path = os.path.join(download_dir, lp_filename)
lp_file_exists = os.path.isfile(lp_download_path)
if only_print_filenames and not lp_file_exists:
print(lp_download_path)
else:
if lp_file_exists:
if file_match_policy == FileMatchPolicy.NAME_SIZE_DEDUP_WITH_SUFFIX:
lp_file_size = os.stat(lp_download_path).st_size
lp_photo_size = version.size
if lp_file_size != lp_photo_size:
lp_download_path = (f"-{lp_photo_size}.").join(
lp_download_path.rsplit(".", 1)
)
logger.debug(
"%s deduplicated", truncate_middle(lp_download_path, 96)
)
lp_file_exists = os.path.isfile(lp_download_path)
if lp_file_exists:
logger.debug(
"%s already exists", truncate_middle(lp_download_path, 96)
)
if not lp_file_exists:
truncated_path = truncate_middle(lp_download_path, 96)
logger.debug("Downloading %s...", truncated_path)
download_result = download.download_media(
logger, dry_run, icloud, photo, lp_download_path, version, lp_size