Files
picpeak/backend/src/utils/filenameSanitizer.js
T
paul 2012b0bab9 Fix language setting not being saved to database on admin settings page
- Added default_language field to general settings state in SettingsPage
- Replaced LanguageSelector component with simple select dropdown on settings page
- Fixed public settings endpoint to read general_default_language from database
- Language setting now properly saved when clicking Save Settings button
- Setting is correctly used by gallery login page and legal pages

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-08 09:49:45 +02:00

57 lines
1.8 KiB
JavaScript

/**
* Sanitize a string to be used as a filename component
* @param {string} str - The string to sanitize
* @param {number} maxLength - Maximum length of the sanitized string
* @returns {string} - Sanitized string
*/
function sanitizeFilename(str, maxLength = 50) {
if (!str) return 'unnamed';
// Convert to string and trim
let sanitized = String(str).trim();
// Replace spaces with underscores
sanitized = sanitized.replace(/\s+/g, '_');
// Remove special characters except hyphens, underscores, and dots
sanitized = sanitized.replace(/[^a-zA-Z0-9_\-\.]/g, '');
// Remove multiple consecutive underscores or hyphens
sanitized = sanitized.replace(/[_\-]{2,}/g, '_');
// Remove leading/trailing underscores or hyphens
sanitized = sanitized.replace(/^[_\-]+|[_\-]+$/g, '');
// Limit length
if (sanitized.length > maxLength) {
sanitized = sanitized.substring(0, maxLength);
}
// If empty after sanitization, use default
if (!sanitized) {
sanitized = 'unnamed';
}
return sanitized;
}
/**
* Generate a photo filename based on event name, category, and counter
* @param {string} eventName - The event name
* @param {string} categoryName - The category name
* @param {number} counter - The photo counter
* @param {string} extension - The file extension (including dot)
* @returns {string} - Generated filename
*/
function generatePhotoFilename(eventName, categoryName, counter, extension) {
const sanitizedEvent = sanitizeFilename(eventName, 30);
const sanitizedCategory = sanitizeFilename(categoryName || 'uncategorized', 20);
const paddedCounter = String(counter).padStart(4, '0');
return `${sanitizedEvent}_${sanitizedCategory}_${paddedCounter}${extension}`;
}
module.exports = {
sanitizeFilename,
generatePhotoFilename
};