file_utilities.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import hashlib
  2. import mimetypes
  3. MEDIA_EXTS_CACHE = []
  4. def media_exts():
  5. """ List of media file extensions from local system mimetypes """
  6. if not MEDIA_EXTS_CACHE:
  7. mimetypes.init()
  8. for ext in mimetypes.types_map:
  9. if mimetypes.types_map[ext].split('/')[0] in ('audio', 'video'):
  10. MEDIA_EXTS_CACHE.append(ext)
  11. return MEDIA_EXTS_CACHE
  12. def is_media_file_ext(ext):
  13. """ Is the given extension a media file extension according to the local system mimetypes """
  14. return ext.lower().lstrip('.') in [e.lower().lstrip('.') for e in media_exts()]
  15. def hash_file(filename):
  16. """ return a SHA256 hash for the given file """
  17. h = hashlib.sha256()
  18. b = bytearray(128 * 1024)
  19. mv = memoryview(b)
  20. with open(filename, 'rb', buffering=0) as f:
  21. for n in iter(lambda: f.readinto(mv), 0):
  22. h.update(mv[:n])
  23. return h.hexdigest()
  24. def is_subdir_of(subject, other):
  25. """ is subject a subdirectory of other """
  26. if not subject.parent:
  27. return False
  28. if subject.parent == other:
  29. return True
  30. return is_subdir_of(subject.parent, other)