const fs = require('fs-extra'); const path = require('path'); const crypto = require('crypto'); const Database = require('better-sqlite3'); const imghash = require('imghash'); const config = require('../config'); /** * ImageHashManager - Manages perceptual hashing of images and stores them in a database * This helps detect duplicate or similar images across different URLs */ class ImageHashManager { constructor() { // Database path const dbDir = path.join(__dirname, '..', 'data'); this.dbPath = path.join(dbDir, 'image_hashes.db'); this.perceptualHashBits = this.getPerceptualHashBits(); // Initialize database this.initDatabase(); } /** * Resolve configured perceptual hash bit length * @returns {number} */ getPerceptualHashBits() { const configuredBits = config.imageHash && Number.isInteger(config.imageHash.perceptualHashBits) ? config.imageHash.perceptualHashBits : 16; // Keep this conservative: even number and within a practical range for imghash. if (configuredBits < 8 || configuredBits > 32 || configuredBits % 2 !== 0) { return 16; } return configuredBits; } /** * Initialize the SQLite database and create tables if they don't exist */ initDatabase() { try { // Ensure data directory exists (synchronously) fs.ensureDirSync(path.dirname(this.dbPath)); // Open database connection this.db = new Database(this.dbPath); // Create tables this.db.exec(` CREATE TABLE IF NOT EXISTS image_hashes ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, perceptual_hash TEXT NOT NULL, content_hash TEXT, file_path TEXT, cached_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, metadata TEXT, alternate_urls TEXT, UNIQUE(url) ); CREATE INDEX IF NOT EXISTS idx_perceptual_hash ON image_hashes(perceptual_hash); CREATE INDEX IF NOT EXISTS idx_url ON image_hashes(url); `); // Backward-compat: add content_hash when upgrading existing databases. const columns = this.db.prepare('PRAGMA table_info(image_hashes)').all(); const hasContentHash = columns.some(col => col.name === 'content_hash'); if (!hasContentHash) { this.db.exec('ALTER TABLE image_hashes ADD COLUMN content_hash TEXT'); } // Create this after migration check to avoid failures on older DBs. this.db.exec('CREATE INDEX IF NOT EXISTS idx_content_hash ON image_hashes(content_hash)'); console.log('[ImageHash] Image hash database initialized'); } catch (error) { console.error('[ImageHash] Error initializing image hash database:', error); throw error; } } /** * Calculate perceptual hash for an image file * @param {string} filePath - Path to the image file * @returns {Promise} - Perceptual hash string */ async calculateHash(filePath) { try { // Use imghash to generate a perceptual hash // This creates a hash that is similar for similar-looking images const hash = await imghash.hash(filePath, this.perceptualHashBits, 'hex'); return hash; } catch (error) { console.error(`Error calculating hash for ${filePath}:`, error); throw error; } } /** * Calculate strong content hash for exact image identity checks * @param {string} filePath - Path to image file * @returns {Promise} - SHA256 hash string */ async calculateContentHash(filePath) { try { const hash = crypto.createHash('sha256'); return await new Promise((resolve, reject) => { const stream = fs.createReadStream(filePath); stream.on('error', reject); stream.on('data', chunk => hash.update(chunk)); stream.on('end', () => resolve(hash.digest('hex'))); }); } catch (error) { console.error(`Error calculating content hash for ${filePath}:`, error); throw error; } } /** * Store image hash in the database * @param {string} url - Original URL of the image * @param {string} hash - Perceptual hash of the image * @param {string} filePath - Path to cached file * @param {Object} metadata - Optional metadata to store * @returns {boolean} - Whether the operation was successful */ storeHash(url, hash, filePath, metadata = null, contentHash = null) { try { const stmt = this.db.prepare(` INSERT INTO image_hashes (url, perceptual_hash, content_hash, file_path, metadata) VALUES (?, ?, ?, ?, ?) ON CONFLICT(url) DO UPDATE SET perceptual_hash = excluded.perceptual_hash, content_hash = excluded.content_hash, file_path = excluded.file_path, cached_at = CURRENT_TIMESTAMP, metadata = excluded.metadata `); const metadataJson = metadata ? JSON.stringify(metadata) : null; stmt.run(url, hash, contentHash, filePath, metadataJson); console.log(`Stored hash for URL: ${url.substring(0, 50)}...`); return true; } catch (error) { console.error('Error storing image hash:', error); return false; } } /** * Process an image file and store its hash * @param {string} url - Original URL of the image * @param {string} filePath - Path to the cached image file * @param {Object} metadata - Optional metadata to store * @returns {Promise<{hash: string, stored: boolean, isDuplicate: boolean}>} */ async processImage(url, filePath, metadata = null) { try { // Check if file exists if (!await fs.pathExists(filePath)) { throw new Error(`File not found: ${filePath}`); } // Calculate perceptual hash const hash = await this.calculateHash(filePath); const contentHash = await this.calculateContentHash(filePath); // Check if this URL already exists const existingByUrl = this.getHashByUrl(url); if (existingByUrl) { console.log(`URL already in database: ${url.substring(0, 50)}...`); return { hash, stored: true, isDuplicate: false }; } // Exact duplicate check: only treat as duplicate when binary content matches. const existingByContentHash = this.getHashByContentHash(contentHash); if (existingByContentHash) { // Same image, different URL - add as alternate URL console.log(`Found exact duplicate image with content hash ${contentHash.substring(0, 12)}..., adding alternate URL`); const added = this.addAlternateUrl(existingByContentHash.url, url); return { hash, stored: added, isDuplicate: true, primaryUrl: existingByContentHash.url }; } // New image - store in database const stored = this.storeHash(url, hash, filePath, metadata, contentHash); return { hash, stored, isDuplicate: false }; } catch (error) { console.error(`Error processing image ${url}:`, error); throw error; } } /** * Get hash for a specific URL * @param {string} url - URL to look up * @returns {Object|null} - Hash data or null if not found */ getHashByUrl(url) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes WHERE url = ? `); const result = stmt.get(url); if (result) { if (result.metadata) { result.metadata = JSON.parse(result.metadata); } if (result.alternate_urls) { result.alternate_urls = JSON.parse(result.alternate_urls); } } return result; } catch (error) { console.error('Error getting hash by URL:', error); return null; } } /** * Get hash record by perceptual hash value * @param {string} hash - Perceptual hash to look up * @returns {Object|null} - Hash data or null if not found */ getHashByHash(hash) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes WHERE perceptual_hash = ? `); const result = stmt.get(hash); if (result) { if (result.metadata) { result.metadata = JSON.parse(result.metadata); } if (result.alternate_urls) { result.alternate_urls = JSON.parse(result.alternate_urls); } } return result; } catch (error) { console.error('Error getting hash by hash value:', error); return null; } } /** * Get all records by perceptual hash value * @param {string} hash - Perceptual hash to look up * @returns {Array} - Hash records (possibly empty) */ getHashesByHash(hash) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes WHERE perceptual_hash = ? ORDER BY cached_at DESC `); const results = stmt.all(hash); return results.map(result => { if (result.metadata) { result.metadata = JSON.parse(result.metadata); } if (result.alternate_urls) { result.alternate_urls = JSON.parse(result.alternate_urls); } return result; }); } catch (error) { console.error('Error getting hashes by hash value:', error); return []; } } /** * Get hash record by content hash value * @param {string} contentHash - SHA256 content hash to look up * @returns {Object|null} - Hash data or null if not found */ getHashByContentHash(contentHash) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes WHERE content_hash = ? `); const result = stmt.get(contentHash); if (result) { if (result.metadata) { result.metadata = JSON.parse(result.metadata); } if (result.alternate_urls) { result.alternate_urls = JSON.parse(result.alternate_urls); } } return result; } catch (error) { console.error('Error getting hash by content hash value:', error); return null; } } /** * Add an alternate URL to an existing hash record * @param {string} primaryUrl - The primary URL of the existing record * @param {string} newUrl - The new URL to add as an alternate * @returns {boolean} - Whether the operation was successful */ addAlternateUrl(primaryUrl, newUrl) { try { // Get existing record const existing = this.getHashByUrl(primaryUrl); if (!existing) { console.error(`Primary URL not found: ${primaryUrl}`); return false; } // Parse existing alternate URLs or create new array let alternateUrls = existing.alternate_urls || []; // Check if this URL is already in alternates or is the primary if (newUrl === primaryUrl || alternateUrls.includes(newUrl)) { console.log(`URL already tracked: ${newUrl.substring(0, 50)}...`); return true; } // Add new URL to alternates alternateUrls.push(newUrl); // Update database const stmt = this.db.prepare(` UPDATE image_hashes SET alternate_urls = ? WHERE url = ? `); stmt.run(JSON.stringify(alternateUrls), primaryUrl); console.log(`Added alternate URL to ${primaryUrl.substring(0, 50)}...`); console.log(` -> ${newUrl.substring(0, 50)}...`); return true; } catch (error) { console.error('Error adding alternate URL:', error); return false; } } /** * Find similar images by comparing perceptual hashes * @param {string} hash - Perceptual hash to compare * @param {number} maxDistance - Maximum hamming distance for similarity (default: 5) * @returns {Array} - Array of similar images */ findSimilarImages(hash, maxDistance = 5) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes `); const allHashes = stmt.all(); const similar = []; // Calculate hamming distance for each hash for (const record of allHashes) { const distance = this.hammingDistance(hash, record.perceptual_hash); if (distance <= maxDistance) { similar.push({ ...record, distance, metadata: record.metadata ? JSON.parse(record.metadata) : null }); } } // Sort by distance (most similar first) similar.sort((a, b) => a.distance - b.distance); return similar; } catch (error) { console.error('Error finding similar images:', error); return []; } } /** * Calculate hamming distance between two hash strings * @param {string} hash1 - First hash * @param {string} hash2 - Second hash * @returns {number} - Hamming distance */ hammingDistance(hash1, hash2) { if (!hash1 || !hash2 || hash1.length !== hash2.length) { return Infinity; } let distance = 0; for (let i = 0; i < hash1.length; i++) { if (hash1[i] !== hash2[i]) { distance++; } } return distance; } /** * Get all stored hashes * @param {number} limit - Maximum number of results (optional) * @returns {Array} - Array of hash records */ getAllHashes(limit = null) { try { let query = 'SELECT * FROM image_hashes ORDER BY cached_at DESC'; if (limit) { query += ` LIMIT ${limit}`; } const stmt = this.db.prepare(query); const results = stmt.all(); return results.map(record => ({ ...record, metadata: record.metadata ? JSON.parse(record.metadata) : null, alternate_urls: record.alternate_urls ? JSON.parse(record.alternate_urls) : [] })); } catch (error) { console.error('Error getting all hashes:', error); return []; } } /** * Delete a hash record by URL * @param {string} url - URL to delete * @returns {boolean} - Whether deletion was successful */ deleteHashByUrl(url) { try { const stmt = this.db.prepare('DELETE FROM image_hashes WHERE url = ?'); const result = stmt.run(url); return result.changes > 0; } catch (error) { console.error('Error deleting hash:', error); return false; } } /** * Clean up hash records for files that no longer exist * @returns {Promise} - Number of records cleaned up */ async cleanupOrphanedHashes() { try { const allHashes = this.getAllHashes(); let cleaned = 0; for (const record of allHashes) { if (record.file_path && !await fs.pathExists(record.file_path)) { if (this.deleteHashByUrl(record.url)) { cleaned++; } } } console.log(`[ImageHash] Cleaned up ${cleaned} orphaned hash records`); return cleaned; } catch (error) { console.error('[ImageHash] Error cleaning up orphaned hashes:', error); return 0; } } /** * Get statistics about the hash database * @returns {Object} - Database statistics */ getStats() { try { const totalStmt = this.db.prepare('SELECT COUNT(*) as count FROM image_hashes'); const total = totalStmt.get().count; const recentStmt = this.db.prepare(` SELECT COUNT(*) as count FROM image_hashes WHERE cached_at > datetime('now', '-7 days') `); const recentWeek = recentStmt.get().count; return { totalImages: total, imagesLastWeek: recentWeek, databasePath: this.dbPath }; } catch (error) { console.error('Error getting stats:', error); return null; } } /** * Close the database connection */ close() { if (this.db) { this.db.close(); console.log('Image hash database connection closed'); } } } module.exports = ImageHashManager;