diff --git a/src/ipod_nano7_db.py b/src/ipod_nano7_db.py index 7feb1cc..2b7ef8f 100644 --- a/src/ipod_nano7_db.py +++ b/src/ipod_nano7_db.py @@ -206,6 +206,7 @@ class Nano7Database: target_dir = self.find_free_music_dir() target_path = os.path.join(self.music_base, target_dir, new_name) + os.makedirs(os.path.dirname(target_path), exist_ok=True) shutil.copy2(filepath, target_path) relative_path = f"{target_dir}/{new_name}" @@ -1102,37 +1103,48 @@ class Nano7Database: # Compute new SHA1 hash new_hash = hashlib.sha1(lib_data).hexdigest() - # Read existing iTunesCDB to extract the header (first 244 bytes) - with open(self.cdb_path, "rb") as f: - cdb_data = f.read() - - # Find zlib header (0x78 0x9c is most common, but also check 0x78 0xda and 0x78 0x01) - zlib_offset = -1 - for pattern in [b"\x78\x9c", b"\x78\xda", b"\x78\x01", b"\x78\x5e"]: - zlib_offset = cdb_data.find(pattern) - if zlib_offset >= 0: - break - if zlib_offset == -1: - logger.error("Could not find zlib header in iTunesCDB") - return - - header = cdb_data[:zlib_offset] - - # Compress Library.itdb - compressed = zlib.compress(lib_data) - - # Write new iTunesCDB - with open(self.cdb_path, "wb") as f: - f.write(header + compressed) + # Read existing iTunesCDB to extract the header (first bytes before zlib) + if not os.path.exists(self.cdb_path): + header = b"\x00" * 244 + header = b"mhfd" + struct.pack("= 0: + break + if zlib_offset == -1: + logger.error("Could not find zlib header in iTunesCDB") + return + + header = cdb_data[:zlib_offset] + + # Compress Library.itdb + compressed = zlib.compress(lib_data) + + # Write new iTunesCDB + with open(self.cdb_path, "wb") as f: + f.write(header + compressed) # Update hash in iTunesCDB.ext - with open(self.cdb_ext_path, "r") as f: - ext_content = f.read() - + if not os.path.exists(self.cdb_ext_path): + ext_content = f"[iTunesCDB]\nitunesdb_hash={new_hash}\n" + else: + with open(self.cdb_ext_path, "r") as f: + ext_content = f.read() + new_ext_content = re.sub(r"itunesdb_hash=\w+", f"itunesdb_hash={new_hash}", ext_content) with open(self.cdb_ext_path, "w") as f: f.write(new_ext_content) - + logger.info(f"Synced iTunesCDB: hash={new_hash}, compressed={len(compressed)} bytes") def sync_locations_cbk(self):