use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use prolink_proto::Slot;
use prolink_rekordbox::{AnlzFile, Library};
use crate::media::MediaDescription;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ServedSlot(Slot);
impl ServedSlot {
pub const SD: Self = Self(Slot::SD);
pub const USB: Self = Self(Slot::USB);
pub const fn new(slot: Slot) -> Option<Self> {
match slot {
Slot::SD | Slot::USB => Some(Self(slot)),
_ => None,
}
}
pub const fn slot(self) -> Slot {
self.0
}
pub const fn export_path(self) -> &'static str {
match self.0 {
Slot::SD => "/B/",
_ => "/C/",
}
}
pub const fn vfs_prefix(self) -> &'static str {
match self.0 {
Slot::SD => "B",
_ => "C",
}
}
}
#[derive(Debug, Default)]
pub struct Analysis {
pub dat: Option<AnlzFile>,
pub ext: Option<AnlzFile>,
}
impl Analysis {
pub fn payload(&self, fourcc: prolink_rekordbox::FourCc) -> &[u8] {
self.dat
.as_ref()
.and_then(|file| file.payload(fourcc))
.or_else(|| self.ext.as_ref().and_then(|file| file.payload(fourcc)))
.unwrap_or_default()
}
}
#[derive(Debug)]
pub struct Medium {
slot: ServedSlot,
library: Library,
root: Option<PathBuf>,
volume_name: String,
created: String,
settings: Vec<u8>,
analysis: Mutex<BTreeMap<u32, std::sync::Arc<Analysis>>>,
}
impl Medium {
pub const PDB_PATH: &'static str = "PIONEER/rekordbox/export.pdb";
pub const SETTINGS_PATH: &'static str = "PIONEER/MYSETTING.DAT";
pub fn from_volume(volume: &Path, slot: ServedSlot) -> crate::Result<Self> {
let pdb = std::fs::read(volume.join(Self::PDB_PATH))
.map_err(crate::Error::io("reading export.pdb"))?;
let library = Library::parse(&pdb)?;
let settings = std::fs::read(volume.join(Self::SETTINGS_PATH))
.ok()
.and_then(|raw| prolink_rekordbox::SettingsFile::parse(&raw).ok())
.map(|file| file.wire_settings().to_vec())
.unwrap_or_default();
let volume_name = volume
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
Ok(Self {
slot,
library,
root: Some(volume.to_path_buf()),
volume_name,
created: String::new(),
settings,
analysis: Mutex::new(BTreeMap::new()),
})
}
pub fn synthetic(slot: ServedSlot, library: Library, volume_name: &str) -> Self {
Self {
slot,
library,
root: None,
volume_name: volume_name.to_owned(),
created: String::new(),
settings: Vec::new(),
analysis: Mutex::new(BTreeMap::new()),
}
}
pub fn slot(&self) -> ServedSlot {
self.slot
}
pub fn library(&self) -> &Library {
&self.library
}
pub fn root(&self) -> Option<&Path> {
self.root.as_deref()
}
pub fn volume_name(&self) -> &str {
&self.volume_name
}
pub fn settings(&self) -> &[u8] {
&self.settings
}
pub fn description(&self) -> MediaDescription {
MediaDescription {
volume_name: self.volume_name.clone(),
created: self.created.clone(),
track_count: u32::try_from(self.library.tracks.len()).unwrap_or(u32::MAX),
playlist_count: u32::try_from(
self.library
.playlists
.values()
.filter(|playlist| !playlist.is_folder)
.count(),
)
.unwrap_or(u32::MAX),
total_bytes: None,
free_bytes: None,
}
}
pub fn artwork(&self, artwork_id: u32) -> Vec<u8> {
let (Some(root), Some(path)) =
(self.root.as_deref(), self.library.artwork.get(&artwork_id))
else {
return Vec::new();
};
std::fs::read(root.join(path.trim_start_matches('/'))).unwrap_or_default()
}
pub fn analysis(&self, track_id: u32) -> std::sync::Arc<Analysis> {
if let Ok(cache) = self.analysis.lock()
&& let Some(cached) = cache.get(&track_id)
{
return std::sync::Arc::clone(cached);
}
let parsed = std::sync::Arc::new(self.read_analysis(track_id));
if let Ok(mut cache) = self.analysis.lock() {
cache.insert(track_id, std::sync::Arc::clone(&parsed));
}
parsed
}
fn read_analysis(&self, track_id: u32) -> Analysis {
let (Some(root), Some(track)) = (self.root.as_deref(), self.library.tracks.get(&track_id))
else {
return Analysis::default();
};
let load = |relative: &str| {
if relative.is_empty() {
return None;
}
let bytes = std::fs::read(root.join(relative.trim_start_matches('/'))).ok()?;
AnlzFile::parse(&bytes).ok()
};
Analysis {
dat: load(&track.analyze_path),
ext: track.analyze_ext_path().as_deref().and_then(load),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_sd_and_usb_can_be_served() {
assert_eq!(ServedSlot::new(Slot::USB), Some(ServedSlot::USB));
assert_eq!(ServedSlot::new(Slot::SD), Some(ServedSlot::SD));
assert_eq!(
ServedSlot::new(Slot::CD),
None,
"a CD has no rekordbox export"
);
assert_eq!(ServedSlot::new(Slot::REKORDBOX), None);
assert_eq!(ServedSlot::new(Slot::NONE), None);
}
#[test]
fn a_slot_knows_where_it_is_exported_from() {
assert_eq!(ServedSlot::SD.export_path(), "/B/");
assert_eq!(ServedSlot::USB.export_path(), "/C/");
}
#[test]
fn two_media_occupy_different_subtrees() {
assert_ne!(ServedSlot::SD.vfs_prefix(), ServedSlot::USB.vfs_prefix());
}
}