diff --git a/src/meta_plugin/magic.rs b/src/meta_plugin/magic.rs index d3578d0..0a4251a 100644 --- a/src/meta_plugin/magic.rs +++ b/src/meta_plugin/magic.rs @@ -28,28 +28,30 @@ impl MagicFileMetaPlugin { } fn get_magic_result(&self, flags: CookieFlags) -> io::Result { - // Create a new cookie with the specific flags for this request - let cookie = Cookie::open(flags) - .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to open magic cookie: {}", e)))?; - cookie.load(&[] as &[&str]) - .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to load magic database: {}", e)))?; + // Use the existing cookie and just change flags + if let Some(cookie) = &self.cookie { + cookie.set_flags(flags) + .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to set magic flags: {}", e)))?; - let result = cookie.buffer(&self.buffer) - .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to analyze buffer: {}", e)))?; + let result = cookie.buffer(&self.buffer) + .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to analyze buffer: {}", e)))?; - // Clean up the result - remove extra whitespace and take first part if needed - let trimmed = result.trim(); - - // For some magic results, we might want just the first part before semicolon or comma - let cleaned = if trimmed.contains(';') { - trimmed.split(';').next().unwrap_or(trimmed).trim() - } else if trimmed.contains(',') && flags.contains(CookieFlags::MIME_TYPE | CookieFlags::MIME_ENCODING) { - trimmed.split(',').next().unwrap_or(trimmed).trim() + // Clean up the result - remove extra whitespace and take first part if needed + let trimmed = result.trim(); + + // For some magic results, we might want just the first part before semicolon or comma + let cleaned = if trimmed.contains(';') { + trimmed.split(';').next().unwrap_or(trimmed).trim() + } else if trimmed.contains(',') && flags.contains(CookieFlags::MIME_TYPE | CookieFlags::MIME_ENCODING) { + trimmed.split(',').next().unwrap_or(trimmed).trim() + } else { + trimmed + }; + + Ok(cleaned.to_string()) } else { - trimmed - }; - - Ok(cleaned.to_string()) + Err(io::Error::new(io::ErrorKind::Other, "Magic cookie not initialized")) + } } fn save_all_magic_metadata(&mut self) -> Result<()> { @@ -109,6 +111,13 @@ impl MetaPlugin for MagicFileMetaPlugin { // Store raw pointer to connection - unsafe but necessary for this design self.conn = Some(conn as *const _ as *mut Connection); + // Initialize the magic cookie once + let cookie = Cookie::open(Default::default()) + .map_err(|e| anyhow::anyhow!("Failed to open magic cookie: {}", e))?; + cookie.load(&[] as &[&str]) + .map_err(|e| anyhow::anyhow!("Failed to load magic database: {}", e))?; + self.cookie = Some(cookie); + Ok(()) }