downloadFile method

Future<String> downloadFile({
  1. required String recordId,
  2. String? outputPath,
})

Downloads file by URL

recordId - recording ID outputPath - path where the file will be saved (optional) Returns saved file path

Implementation

Future<String> downloadFile({
  required String recordId,
  String? outputPath,
}) async {
  try {
    final originalHeaders = Map<String, dynamic>.from(_dio.options.headers);
    _dio.options.headers = {
      'x-gladia-key': apiKey,
    };

    // Set parameters for downloading file
    final options = Options(
      responseType: ResponseType.bytes,
      followRedirects: true,
    );

    final response = await _dio.get(
      'v2/pre-recorded/$recordId/file',
      options: options,
    );

    _dio.options.headers = originalHeaders;

    if (response.data == null) {
      throw GladiaApiException(message: 'Empty response from server');
    }

    // Determine file name from headers or generate randomly
    String fileName = 'gladia_audio_$recordId.mp3';

    // If there is Content-Disposition header, try to extract file name
    final contentDisposition = response.headers.value('content-disposition');
    if (contentDisposition != null &&
        contentDisposition.contains('filename=')) {
      final match =
          RegExp(r'filename="?([^"]+)"?').firstMatch(contentDisposition);
      if (match != null) {
        fileName = match.group(1) ?? fileName;
      }
    }

    // Determine save path
    final savePath = outputPath ?? fileName;

    // Create file and write data
    final file = File(savePath);
    await file.writeAsBytes(response.data as List<int>);

    return file.path;
  } on DioException catch (e) {
    throw GladiaApiException.fromDioError(e);
  } catch (e) {
    if (e is GladiaApiException) {
      rethrow;
    }
    throw GladiaApiException(message: e.toString());
  }
}