addFileToMedia method

Future<String> addFileToMedia(
  1. {required File exportFile,
  2. required String preferredName,
  3. required String mimeType,
  4. bool fallback = false}
)

Add a file to Anki media. mimeType can be 'image' or 'audio'. preferredName is used as a prefix to the file when exported to the media store. Returns the name of the file once successfully added to Anki media.

Implementation

Future<String> addFileToMedia({
  required File exportFile,
  required String preferredName,
  required String mimeType,
  bool fallback = false,
}) async {
  late File destinationFile;
  if (mimeType == 'image') {
    destinationFile = getImageExportFile(fallback: fallback);
  } else if (mimeType == 'audio') {
    destinationFile = getAudioExportFile(fallback: fallback);
  } else {
    throw Exception('Invalid mime type, must be image or audio');
  }

  if (destinationFile.existsSync()) {
    destinationFile.deleteSync();
  }

  String destinationPath = destinationFile.path;
  if (mimeType == 'image') {
    File compressedFile = getImageCompressedFile(fallback: fallback);
    if (compressedFile.existsSync()) {
      compressedFile.deleteSync();
    }
    await FlutterImageCompress.compressAndGetFile(
      exportFile.path,
      compressedFile.path,
      quality: 70,
      keepExif: true,
    );

    debugPrint('Original image size: ${exportFile.lengthSync()} bytes');
    debugPrint('Compressed image size: ${compressedFile.lengthSync()} bytes');

    compressedFile.copySync(destinationPath);
  } else {
    exportFile.copySync(destinationPath);
  }

  try {
    String response = await methodChannel.invokeMethod(
      'addFileToMedia',
      <String, String>{
        'filename': destinationPath,
        'preferredName': preferredName,
        'mimeType': mimeType,
      },
    );
    debugPrint('Added $mimeType for [$preferredName] to Anki media');
    if (destinationFile.existsSync()) {
      destinationFile.deleteSync();
    }

    return response;
  } on PlatformException {
    if (fallback) {
      Fluttertoast.showToast(
        msg: t.error_export_media_ankidroid,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
      );

      rethrow;
    } else {
      return addFileToMedia(
        exportFile: exportFile,
        preferredName: preferredName,
        mimeType: mimeType,
        fallback: true,
      );
    }
  }
}