""" Mail utility helper functions. """ import os import json import time from datetime import datetime def truncate_id(message_id, length=8): """ Truncate a message ID to a reasonable length for display. Args: message_id (str): The message ID to truncate. length (int): The number of characters to keep. Returns: str: The truncated message ID. """ if not message_id: return "" if len(message_id) <= length: return message_id return f"{message_id[:length]}..." def load_last_sync_timestamp(): """ Load the last synchronization timestamp from a file. Returns: float: The timestamp of the last synchronization, or 0 if not available. """ try: with open('sync_timestamp.json', 'r') as f: data = json.load(f) return data.get('timestamp', 0) except (FileNotFoundError, json.JSONDecodeError): return 0 def save_sync_timestamp(): """ Save the current timestamp as the last synchronization timestamp. Returns: None """ current_time = time.time() with open('sync_timestamp.json', 'w') as f: json.dump({'timestamp': current_time}, f) def format_datetime(dt_str, format_string="%m/%d %I:%M %p"): """ Format a datetime string from ISO format. Args: dt_str (str): ISO format datetime string. format_string (str): Format string for the output. Returns: str: Formatted datetime string. """ if not dt_str: return "" try: dt = datetime.fromisoformat(dt_str.replace('Z', '+00:00')) return dt.strftime(format_string) except (ValueError, AttributeError): return dt_str def safe_filename(filename): """ Convert a string to a safe filename. Args: filename (str): Original filename. Returns: str: Safe filename with invalid characters replaced. """ invalid_chars = '<>:"/\\|?*' for char in invalid_chars: filename = filename.replace(char, '_') return filename def ensure_directory_exists(directory): """ Ensure that a directory exists, creating it if necessary. Args: directory (str): The directory path to check/create. Returns: None """ if not os.path.exists(directory): os.makedirs(directory) def parse_maildir_name(filename): """ Parse a Maildir filename to extract components. Args: filename (str): The maildir filename. Returns: tuple: (message_id, flags) components of the filename. """ # Maildir filename format: unique-id:flags if ':' in filename: message_id, flags = filename.split(':', 1) else: message_id = filename flags = '' return message_id, flags