symuid-import-cmus 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import datetime as dt
  4. import os
  5. import symuid
  6. import symuid.library.cmus
  7. FILE_PREFIX = b'CTC'
  8. VERSION_LENGTH = 1
  9. SUPPORTED_VERSION = b'\x0c'
  10. # always big endian, see cache_init()
  11. FLAGS_BYTEORDER = 'big'
  12. FLAGS_LENGTH = 4
  13. FLAG_64_BIT = 0x01
  14. def import_track(cmus_track):
  15. if cmus_track.play_count > 0:
  16. print(cmus_track.play_count, cmus_track.path)
  17. def symuid_import_cmus(cache_path):
  18. with open(os.path.expanduser(cache_path), 'rb') as cache:
  19. # see cache.c cache_init()
  20. assert cache.read(len(FILE_PREFIX)) == FILE_PREFIX
  21. cache_version = cache.read(VERSION_LENGTH)
  22. assert cache_version == SUPPORTED_VERSION, cache_version
  23. flags = int.from_bytes(
  24. cache.read(FLAGS_LENGTH),
  25. byteorder=FLAGS_BYTEORDER, # persistent
  26. )
  27. assert flags & FLAG_64_BIT
  28. # support no other flags
  29. assert flags & ~FLAG_64_BIT == 0, flags
  30. # size includes size itself
  31. while True:
  32. size = symuid.library.cmus._int_from_bytes_sys(cache.read(4))
  33. if size == 0:
  34. break
  35. cmus_track = symuid.library.cmus.Track(size, cache.read(size - 4))
  36. import_track(cmus_track)
  37. # see cache.c write_ti ALIGN
  38. cache.read((-size) % 8)
  39. def _init_argparser():
  40. import argparse
  41. argparser = argparse.ArgumentParser(description=None)
  42. argparser.add_argument(
  43. 'cache_path',
  44. nargs='?',
  45. default='~/.config/cmus/cache',
  46. help='(default: %(default)r)',
  47. )
  48. return argparser
  49. def main(argv):
  50. argparser = _init_argparser()
  51. args = argparser.parse_args(argv[1:])
  52. symuid_import_cmus(**vars(args))
  53. return 0
  54. if __name__ == "__main__":
  55. import sys
  56. sys.exit(main(sys.argv))