67 lines
No EOL
2.1 KiB
Python
67 lines
No EOL
2.1 KiB
Python
"""
|
|
Utility functions for MIME type handling and file format determination.
|
|
"""
|
|
|
|
def isTextMimeType(mimeType: str) -> bool:
|
|
"""
|
|
Determines if a MIME type represents a text format that should not be base64 encoded.
|
|
|
|
Args:
|
|
mimeType: The MIME type to check
|
|
|
|
Returns:
|
|
True if the content is a text format, False otherwise
|
|
"""
|
|
return (
|
|
mimeType.startswith("text/") or
|
|
mimeType in [
|
|
"application/json",
|
|
"application/xml",
|
|
"application/javascript",
|
|
"application/x-python",
|
|
"image/svg+xml"
|
|
]
|
|
)
|
|
|
|
def determineContentEncoding(fileName: str, content: any, mimeType: str = None) -> bool:
|
|
"""
|
|
Determines if content should be base64 encoded based on file type and MIME type.
|
|
|
|
Args:
|
|
fileName: Name of the file including extension
|
|
content: The content of the file
|
|
mimeType: Optional MIME type of the content
|
|
|
|
Returns:
|
|
True if content should be base64 encoded, False otherwise
|
|
"""
|
|
# If MIME type is provided, use it for determination
|
|
if mimeType:
|
|
if isTextMimeType(mimeType):
|
|
return False if isinstance(content, str) else True
|
|
|
|
# Import here to avoid circular imports
|
|
import os
|
|
|
|
# Extract file extension
|
|
_, extension = os.path.splitext(fileName)
|
|
extension = extension.lower().lstrip('.')
|
|
|
|
# Determine if we should base64 encode based on file type
|
|
text_extensions = {'txt', 'csv', 'json', 'xml', 'html', 'md', 'svg', 'js', 'css', 'py'}
|
|
|
|
# If it's a text format and content is a string, don't base64 encode
|
|
if extension in text_extensions and isinstance(content, str):
|
|
return False
|
|
|
|
# For binary formats, always base64 encode
|
|
binary_extensions = {'jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'zip', 'rar'}
|
|
if extension in binary_extensions:
|
|
return True
|
|
|
|
# If content is bytes, base64 encode regardless of extension
|
|
if isinstance(content, bytes):
|
|
return True
|
|
|
|
# Default for unknown types
|
|
return not isinstance(content, str) |