flush method

Future<void> flush(
  1. File flushFile,
  2. IOSink flushSink
)

Flushes data to the file, compress, encrypt, and close it.

Implementation

Future<void> flush(File flushFile, IOSink flushSink) async {
  // fast exit if we're already flushing this file/sink
  if (flushSink.hashCode == _flushingSink) return;

  _flushingSink = flushSink.hashCode;

  // Reset the file (setting it and its name and sink to null),
  // so a new file (and sink) can be created.
  _sink = null;
  _initialized = false;
  _filename = null;
  _file = null;

  // Start creating a new sink (and file) to be used in parallel
  // to flushing this file.
  // sink.then((_) {});

  final jsonFilePath = flushFile.path;
  var finalFilePath = jsonFilePath;

  info("Written JSON to file '$jsonFilePath'. Closing it.");
  flushSink.write('{}]\n'); // add empty object {} and ] to make file valid

  // once finished closing the file, then zip and encrypt it
  flushSink.close().then((value) {
    if (fileDataEndPoint.zip) {
      // create a new zip file and add the JSON file to this zip file
      final encoder = ZipFileEncoder();
      final jsonFile = File(jsonFilePath);
      finalFilePath = '$jsonFilePath.zip';
      encoder.create(finalFilePath);
      encoder.addFile(jsonFile);
      encoder.close();

      // once the file is zipped to a new zip file, delete the old JSON file
      jsonFile.delete();
    }

    // encrypt the zip file
    if (fileDataEndPoint.encrypt) {
      //TODO : implement encryption
      // if the encrypted file gets another name, remember to
      // update _jsonFilePath
      addEvent(FileDataManagerEvent(
          FileDataManagerEventTypes.FILE_ENCRYPTED, finalFilePath));
    }

    addEvent(FileDataManagerEvent(
        FileDataManagerEventTypes.FILE_CLOSED, finalFilePath));
  });
}