saveDecryptedContent function
Saves decrypted content to a file, handling different file formats appropriately.
Attempts to save as JSON if possible, falls back to binary or text based on file type.
Implementation
Future<void> saveDecryptedContent(
String decryptedContent,
String saveFilePath,
) async {
final file = File(saveFilePath);
// Ensure the parent directory exists.
await file.parent.create(recursive: true);
try {
// First, try to detect content type.
if (_isLikelyJson(decryptedContent)) {
// Try to parse and save as formatted JSON.
try {
final jsonData = jsonDecode(decryptedContent);
await file.writeAsString(
const JsonEncoder.withIndent(' ').convert(jsonData),
);
return;
} catch (jsonError) {
debugPrint('JSON parsing failed despite looking like JSON: $jsonError');
// Continue to other options if JSON parsing fails
}
}
// For non-text files, try base64 decoding if it looks like base64.
if (!isTextFile(saveFilePath) && _isLikelyBase64(decryptedContent)) {
try {
final bytes = base64Decode(decryptedContent);
await file.writeAsBytes(bytes);
return;
} catch (base64Error) {
debugPrint(
'Base64 decode failed despite looking like base64: $base64Error',
);
// Continue to text handling if base64 fails
}
}
// Default: treat as plain text.
await file.writeAsString(decryptedContent);
} catch (e) {
throw Exception('Failed to save file: ${e.toString()}');
}
}