]> git.treefish.org Git - photosort.git/blob - src/photosort.py
re-implemented cleanup
[photosort.git] / src / photosort.py
1 #!/usr/bin/env python3
2
3 import argparse
4 import datetime
5 import logging
6 import os
7
8 import misc
9
10 parser = argparse.ArgumentParser(description='Process some integers.')
11 parser.add_argument('SOURCE_DIR', type=str, help='source directory')
12 parser.add_argument('DEST_DIR', type=str, help='target directory')
13 parser.add_argument('-c', '--cleanup', action='store_true', dest='cleanup',
14                     default=False, help='clean-up source dir')
15 parser.add_argument('-v', '--verbose', action='store_true', dest='verbose',
16                     default=False, help='enable verbose output')
17 parser.add_argument('-q', '--quiet', action='store_true', dest='quiet',
18                     default=False, help='suppress non-error output')
19
20 args = parser.parse_args()
21
22 if args.verbose:
23     log_level = logging.INFO
24 elif args.quiet:
25     log_level = logging.ERROR
26 else:
27     log_level = logging.WARNING
28
29 logging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s',
30                     level=log_level, datefmt='%m/%d/%Y %H:%M:%S')
31
32 for src_file_name, src_file_path in misc.walk_media_files(args.SOURCE_DIR):
33     logging.info('Processing %s...', src_file_name)
34
35     try:
36         meta_time = misc.extract_timestamp(src_file_path, use_meta=True)
37
38         dst_dir = os.path.join(args.DEST_DIR,
39                                datetime.datetime.fromtimestamp(meta_time).strftime("%Y/%m"))
40         dst_file_path = os.path.join(dst_dir, src_file_name)
41
42         if not os.path.exists(dst_file_path):
43             alt_dst_dir = misc.find_file(args.DEST_DIR,
44                                          src_file_name,
45                                          os.path.getsize(src_file_path),
46                                          exclude_dir=args.SOURCE_DIR)
47             if alt_dst_dir:
48                 dst_dir = alt_dst_dir
49                 dst_file_path = os.path.join(dst_dir, src_file_name)
50
51         if not os.path.exists(dst_file_path):
52             if not os.path.exists(dst_dir):
53                 os.makedirs(dst_dir)
54             misc.import_file(src_file_path, dst_file_path)
55         else:
56             src_time = misc.extract_timestamp(src_file_path)
57             dst_time = misc.extract_timestamp(dst_file_path)
58             if src_time > dst_time:
59                 misc.import_file(src_file_path, dst_file_path)
60
61         if args.cleanup:
62             os.remove(src_file_path)
63
64     except Exception as e:
65         logging.error('Error processing %s: %s', src_file_path, str(e))
66
67 if args.cleanup:
68     misc.cleanup_dir(args.SOURCE_DIR)