file_utilities.py 1.6 KB

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