initialize method

  1. @override
Future<void> initialize()
override

Initialize the database - only called when the BaseDownloader is created with this object, which happens when the FileDownloader singleton is instantiated, OR as part of a migration away from this database type.

Migrates the data from stored name and version to the current name and version, if needed This call runs async with the rest of the initialization

Implementation

@override
Future<void> initialize() async {
  final (currentName, currentVersion) = currentDatabaseVersion;
  final (storedName, storedVersion) = await storedDatabaseVersion;
  if (storedName != currentName) {
    log.warning('Cannot migrate from database name $storedName');
    return;
  }
  if (storedVersion == currentVersion) {
    return;
  }
  log.fine(
      'Migrating $currentName database from version $storedVersion to $currentVersion');
  switch (storedVersion) {
    case 0:
      // move files from docDir to supportDir
      final docDir = await getApplicationDocumentsDirectory();
      final supportDir = await getApplicationSupportDirectory();
      for (String path in [
        resumeDataPath,
        pausedTasksPath,
        taskRecordsPath
      ]) {
        try {
          final fromPath = join(docDir.path, path);
          if (await Directory(fromPath).exists()) {
            log.finest('Moving $path to support directory');
            final toPath = join(supportDir.path, path);
            await Directory(toPath).create(recursive: true);
            await Directory(fromPath).list().forEach((entity) {
              if (entity is File) {
                entity.copySync(join(toPath, basename(entity.path)));
              }
            });
            await Directory(fromPath).delete(recursive: true);
          }
        } catch (e) {
          log.fine('Error migrating database for path $path: $e');
        }
      }

    default:
      log.warning('Illegal starting version: $storedVersion');
  }
  await _db
      .collection(metaDataCollection)
      .doc('metaData')
      .set({'version': currentVersion});
}