file_utilities.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import hashlib
  2. import mimetypes
  3. import os
  4. import platform
  5. import subprocess
  6. import sys
  7. MEDIA_EXTS_CACHE = ['.mp3', '.wma', '.flac', '.mp4']
  8. def media_exts():
  9. """ List of media file extensions from local system mimetypes """
  10. # if not MEDIA_EXTS_CACHE:
  11. # mimetypes.init()
  12. # for ext in mimetypes.types_map:
  13. # if mimetypes.types_map[ext].split('/')[0] in ('audio', 'video'):
  14. # MEDIA_EXTS_CACHE.append(ext)
  15. return MEDIA_EXTS_CACHE
  16. def is_media_file_ext(ext):
  17. """ Is the given extension a media file extension according to the local system mimetypes """
  18. return ext.lower().lstrip('.') in [e.lower().lstrip('.') for e in media_exts()]
  19. def hash_file(filename):
  20. """ return a SHA256 hash for the given file """
  21. h = hashlib.sha256()
  22. b = bytearray(128 * 1024)
  23. mv = memoryview(b)
  24. with open(filename, 'rb', buffering=0) as f:
  25. for n in iter(lambda: f.readinto(mv), 0):
  26. h.update(mv[:n])
  27. return h.hexdigest()
  28. def is_subdir_of(subject, other):
  29. """ is subject a subdirectory of other """
  30. if not subject.parent:
  31. return False
  32. if subject.parent == other:
  33. return True
  34. return is_subdir_of(subject.parent, other)
  35. def open_file(path_):
  36. if sys.platform == 'darwin':
  37. subprocess.check_call(['open', str(path_)])
  38. elif sys.platform == 'linux':
  39. subprocess.check_call(['xdg-open', str(path_)])
  40. elif sys.platform == 'win32':
  41. subprocess.check_call(['explorer', str(path_)])
  42. else:
  43. raise RuntimeError(f"Unsupported platform {sys.platform}")