uploadFileToPod function

Future<SolidFunctionCallStatus> uploadFileToPod({
  1. required String filePath,
  2. required String targetPath,
  3. required BuildContext context,
  4. String? customFileName,
  5. void onProgressChange(
    1. bool
    )?,
  6. void onSuccess()?,
})

Handles file upload to POD with encryption.

Returns a Future<SolidFunctionCallStatus> indicating the upload result.

Implementation

Future<SolidFunctionCallStatus> uploadFileToPod({
  required String filePath,
  required String targetPath,
  required BuildContext context,
  String? customFileName,
  void Function(bool)? onProgressChange,
  void Function()? onSuccess,
}) async {
  try {
    onProgressChange?.call(true);

    final file = File(filePath);
    String fileContent;

    // Handle text vs binary files.

    if (isTextFile(filePath)) {
      fileContent = await file.readAsString();
    } else {
      final bytes = await file.readAsBytes();
      fileContent = base64Encode(bytes);
    }

    // Sanitise filename and handle custom name if provided.

    String sanitizedFileName = customFileName ?? path.basename(filePath);
    sanitizedFileName = sanitizedFileName
        .replaceAll(RegExp(r'[^a-zA-Z0-9._-]'), '_')
        .replaceAll(RegExp(r'\.enc\.ttl$'), '');

    final remoteFileName = '$sanitizedFileName.enc.ttl';

    // Construct upload path.

    String uploadPath = '$targetPath/$remoteFileName';
    uploadPath =
        uploadPath.replaceAll(RegExp(r'^/+'), ''); // Remove leading slashes

    // Guard against using context across async gaps.

    if (!context.mounted) {
      debugPrint('Widget is no longer mounted, skipping upload.');
      return SolidFunctionCallStatus.fail;
    }

    // Upload file with encryption.

    final result = await writePod(
      uploadPath,
      fileContent,
      context,
      const Text('Upload'),
      encrypted: true,
    );

    if (result == SolidFunctionCallStatus.success) {
      onSuccess?.call();
    }

    return result;
  } finally {
    onProgressChange?.call(false);
  }
}