deleteImageByHash<DataT extends Data> method

Future<String?> deleteImageByHash<DataT extends Data>(
  1. DataT? data,
  2. String hash, {
  3. String? canonicalHash,
  4. Data? caller,
  5. bool forceUpdate = false,
})

deletes an image specified by its hash and returns the response

Implementation

Future<String?> deleteImageByHash<DataT extends Data>(
  DataT? data,
  String hash, {
  String? canonicalHash,
  Data? caller,
  bool forceUpdate = false,
}) async {
  final requested = hash.trim();
  final canonical = (canonicalHash ?? '').trim();
  final scope = _scopeForData(data, caller: caller).trim();

  final hashRefs = <String>{};
  final pathRefs = <String>{};

  void addRef(String value) {
    final v = value.trim();
    if (v.isEmpty) return;
    if (v.contains('/')) {
      pathRefs.add(v);
    } else {
      hashRefs.add(v);
    }
  }

  addRef(requested);
  addRef(canonical);

  for (final ref in [requested, canonical]) {
    if (ref.isEmpty || !ref.contains('/')) continue;
    try {
      final mappedHash = await OP.lookupHashForImageName(ref, scope: scope);
      if (mappedHash != null && mappedHash.trim().isNotEmpty) {
        addRef(mappedHash);
      }
    } catch (_) {}
  }

  for (final h in hashRefs.toList(growable: false)) {
    try {
      final mappedName = await OP.lookupImageNameForHash(h, scope: scope);
      if (mappedName != null && mappedName.trim().isNotEmpty) {
        addRef(mappedName);
      }
    } catch (_) {}
    if (scope.isNotEmpty) addRef('$scope/$h');
  }

  final allRefs = <String>{...hashRefs, ...pathRefs};

  if ((forceUpdate || caller != null) && data != null) {
    try {
      data.imagehashes ??= <String>[];
      data.imagehashes!.removeWhere((h) => allRefs.contains(h));
      if (data.mainhash != null && allRefs.contains(data.mainhash!)) {
        data.mainhash = null;
      }
      await storeData<DataT>(data, forId: caller?.id ?? await API().rootID);
    } catch (e) {
      debugPrint('failed to remove image references locally: $e');
    }
  }

  for (final pathRef in pathRefs) {
    await _deleteStoredImageQuietly(pathRef);
  }
  for (final hashRef in hashRefs) {
    await _deleteStoredImageQuietly(hashRef);
    if (scope.isNotEmpty) {
      await _deleteStoredImageQuietly('$scope/$hashRef');
    }
    await OP.unindexImageHash(hash: hashRef, scope: scope);
  }
  return 'success';
}