]> git.treefish.org Git - photosort.git/blob - src/misc.py
e02b8179d58e79ef90938914c9d630557b0ccb2e
[photosort.git] / src / misc.py
1 import mimetypes
2 import os
3 import shutil
4
5 def walk_media_files(dir_path):
6     for root, dirs, files in os.walk(dir_path):
7         for f in files:
8             file_path = os.path.join(root, f)
9             if _is_media_file(file_path):
10                 yield (f, file_path)
11
12 def extract_timestamp(file_path):
13     return os.path.getmtime(file_path)
14
15 def find_file(dir_path, file_name, file_size, exclude_dir):
16     for root, dirs, files in os.walk(dir_path):
17         if root == exclude_dir:
18             continue
19         for f in files:
20             if f == file_name:
21                 full_path = os.path.join(root, f)
22                 if os.path.getsize(full_path) == file_size:
23                     return root
24     return None
25
26 def import_file(src_file_path, dst_file_path, move=False):
27     shutil.copyfile(src_file_path, dst_file_path)
28     src_stat = os.stat(src_file_path)
29     dst_stat = os.stat(dst_file_path)
30     os.utime( dst_file_path, ns=(dst_stat.st_atime_ns, src_stat.st_mtime_ns) )
31
32 def delete_dir_contents(dir_path):
33     for file_name in os.listdir(dir_path):
34         file_path = os.path.join(dir_path, file_name)
35         if os.path.isfile(file_path) or os.path.islink(file_path):
36             os.unlink(file_path)
37         elif os.path.isdir(file_path):
38             shutil.rmtree(file_path)
39
40 def _is_media_file(file_path):
41     if not os.path.isfile(file_path):
42         return False
43     mime_type = mimetypes.guess_type(file_path)[0]
44     if not mime_type:
45         return False
46     if not mime_type.split('/')[0] in ['image', 'video']:
47         return False
48     return True