]> git.treefish.org Git - photosort.git/blob - src/misc.py
refactoring
[photosort.git] / src / misc.py
1 import datetime
2 import mimetypes
3 import os
4 import PIL.Image
5 import shutil
6
7 def walk_media_files(dir_path):
8     for root, dirs, files in os.walk(dir_path):
9         for f in files:
10             file_path = os.path.join(root, f)
11             if _is_media_file(file_path):
12                 yield (f, file_path)
13
14 def extract_timestamp(file_path, use_exif=False):
15     if use_exif and _is_media_file(file_path, types=['image']):
16         with PIL.Image.open(file_path) as image:
17             exif = image._getexif()
18             if exif and 36867 in exif:
19                 return int( datetime.datetime
20                             .strptime(exif[36867], '%Y:%m:%d %H:%M:%S')
21                             .timestamp() )
22     return os.path.getmtime(file_path)
23
24 def find_file(dir_path, file_name, file_size, exclude_dir):
25     for root, dirs, files in os.walk(dir_path):
26         if root == exclude_dir:
27             continue
28         for f in files:
29             if f == file_name:
30                 full_path = os.path.join(root, f)
31                 if os.path.getsize(full_path) == file_size:
32                     return root
33     return None
34
35 def import_file(src_file_path, dst_file_path):
36     shutil.copyfile(src_file_path, dst_file_path)
37     src_stat = os.stat(src_file_path)
38     dst_stat = os.stat(dst_file_path)
39     os.utime( dst_file_path, ns=(dst_stat.st_atime_ns, src_stat.st_mtime_ns) )
40
41 def delete_dir_contents(dir_path):
42     for file_name in os.listdir(dir_path):
43         file_path = os.path.join(dir_path, file_name)
44         if os.path.isfile(file_path) or os.path.islink(file_path):
45             os.unlink(file_path)
46         elif os.path.isdir(file_path):
47             shutil.rmtree(file_path)
48
49 def _is_media_file(file_path, types=['image', 'video']):
50     if not os.path.isfile(file_path):
51         return False
52     mime_type = mimetypes.guess_type(file_path)[0]
53     if not mime_type:
54         return False
55     if not mime_type.split('/')[0] in types:
56         return False
57     return True