moveCramKeyToStale method

Future<Map<String, dynamic>> moveCramKeyToStale(
  1. String atSign
)

Implementation

Future<Map<String, dynamic>> moveCramKeyToStale(String atSign) async {
  await ensureReady();

  final normalized = normalizeAtSign(atSign);
  final fileName = _fileNameForAtSign(atSign);
  final probe = path.canonicalize(path.join(_directory!.path, fileName));
  if (!path.isWithin(_directory!.path, probe)) {
    return {
      'atSign': normalized,
      'status': 'error',
      'error': 'Invalid atSign name',
    };
  }

  File? sourceFile;
  String? fromLabel;
  final pendingFile = File(path.join(_directory!.path, fileName));
  final archivedFile = File(path.join(_oldDirectory!.path, fileName));

  if (await pendingFile.exists()) {
    sourceFile = pendingFile;
    fromLabel = 'pending';
  } else if (await archivedFile.exists()) {
    sourceFile = archivedFile;
    fromLabel = 'archived';
  }

  if (sourceFile == null) {
    return {'atSign': normalized, 'status': 'not_found'};
  }

  try {
    final destPath = path.join(_staleDirectory!.path, fileName);
    try {
      await sourceFile.rename(destPath);
    } catch (_) {
      await sourceFile.copy(destPath);
      await sourceFile.delete();
    }
    if (fromLabel == 'pending' && await archivedFile.exists()) {
      try {
        await archivedFile.delete();
      } catch (_) {}
    }
    return {
      'atSign': normalized,
      'status': 'moved',
      'to': destPath,
      'from': fromLabel,
    };
  } catch (e) {
    return {
      'atSign': normalized,
      'status': 'error',
      'error': e.toString(),
    };
  }
}