Browse Source

symuid-import-cmus: refactor attr parsing

Fabian Peter Hammerle 6 years ago
parent
commit
37e166e7dd
1 changed files with 36 additions and 8 deletions
  1. 36 8
      symuid-import-cmus

+ 36 - 8
symuid-import-cmus

@@ -15,6 +15,12 @@ SUPPORTED_VERSION = b'\x0c'
 FLAGS_BYTEORDER = 'big'
 FLAGS_LENGTH = 4
 FLAG_64_BIT = 0x01
+RESERVED_PAD_REGEX = rb'\xff{16,}'
+STRING_TERMINATOR = b'\x00'
+
+
+def _int_from_bytes_sys(data_bytes):
+    return int.from_bytes(data_bytes, byteorder=sys.byteorder)
 
 
 class Track:
@@ -35,10 +41,27 @@ class Track:
         };
         """
         assert len(cache_bytes) + 4 == cache_size
-        self._play_count = int.from_bytes(cache_bytes[0:4], byteorder=sys.byteorder)
-        self._path = cache_bytes.split(b'\xff' * 56)[1].split(b'\x00')[0]
-        if self._play_count > 0:
-            print(self._play_count, self._path.decode())
+        self._play_count = _int_from_bytes_sys(cache_bytes[0:4])
+        # self._mtime = _int_from_bytes_sys(cache_bytes[4:12])
+        # self._duration_seconds = _int_from_bytes_sys(cache_bytes[12:16])
+        # self._bitrate = _int_from_bytes_sys(cache_bytes[16:20])
+        # self._bpm = _int_from_bytes_sys(cache_bytes[20:24])
+        strings = re.split(RESERVED_PAD_REGEX, cache_bytes)[1] \
+            .split(STRING_TERMINATOR)
+        self._path = strings[0]
+
+    @property
+    def path(self):
+        return self._path
+
+    @property
+    def play_count(self):
+        return self._play_count
+
+
+def import_track(cmus_track):
+    if cmus_track.play_count > 0:
+        print(cmus_track.play_count, cmus_track.path)
 
 
 def symuid_import_cmus(cache_path):
@@ -47,15 +70,20 @@ def symuid_import_cmus(cache_path):
         assert cache.read(len(FILE_PREFIX)) == FILE_PREFIX
         cache_version = cache.read(VERSION_LENGTH)
         assert cache_version == SUPPORTED_VERSION, cache_version
-        flags = int.from_bytes(cache.read(FLAGS_LENGTH), byteorder=FLAGS_BYTEORDER)
-        # only support 64-bit flag
+        flags = int.from_bytes(
+            cache.read(FLAGS_LENGTH),
+            byteorder=FLAGS_BYTEORDER,  # persistent
+        )
+        assert flags & FLAG_64_BIT
+        # support no other flags
         assert flags & ~FLAG_64_BIT == 0, flags
         # size includes size itself
         while True:
-            size = int.from_bytes(cache.read(4), byteorder=sys.byteorder)
+            size = _int_from_bytes_sys(cache.read(4))
             if size == 0:
                 break
-            Track(size, cache.read(size - 4))
+            cmus_track = Track(size, cache.read(size - 4))
+            import_track(cmus_track)
             # see cache.c write_ti ALIGN
             cache.read((-size) % 8)