import hashlib import mimetypes MEDIA_EXTS_CACHE = [] def media_exts(): """ List of media file extensions from local system mimetypes """ if not MEDIA_EXTS_CACHE: mimetypes.init() for ext in mimetypes.types_map: if mimetypes.types_map[ext].split('/')[0] in ('audio', 'video'): MEDIA_EXTS_CACHE.append(ext) return MEDIA_EXTS_CACHE def is_media_file_ext(ext): """ Is the given extension a media file extension according to the local system mimetypes """ return ext.lower().lstrip('.') in [e.lower().lstrip('.') for e in media_exts()] def hash_file(filename): """ return a SHA256 hash for the given file """ h = hashlib.sha256() b = bytearray(128 * 1024) mv = memoryview(b) with open(filename, 'rb', buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) return h.hexdigest() def is_subdir_of(subject, other): """ is subject a subdirectory of other """ if not subject.parent: return False if subject.parent == other: return True return is_subdir_of(subject.parent, other)