getImageByHash method
Implementation
RequestAndParser<http.BaseResponse, ImageData?> getImageByHash(String hash,
{Data? owner}) {
final isPathHash = hash.contains('/');
final rd = switch (kIsWeb) {
true => RequestData('/login'),
false => RequestData(
_getImageFromHash_r,
json: {
'hash': hash,
},
returnsBinary: true,
)
};
parser(http.BaseResponse _res) async {
if (kIsWeb)
return ImageData(
Image(
image: NetworkImage("$_baseurl/get/$hash",
headers: {HttpHeaders.authorizationHeader: _api_key})),
id: hash,
name: _stripImageExtension(hash.split('/').last));
final res = _res.forceRes();
if (res == null || res.statusCode ~/ 100 != 2)
return null;
else {
try {
final scope = owner != null ? API().local.scopeFor(owner) : '';
final filename = _extractBackendFilename(res.headers);
String storedName;
String? displayName;
if (!isPathHash && filename != null && filename.isNotEmpty) {
final base = filename;
storedName = (scope.isNotEmpty) ? '$scope/$base' : base;
displayName = _stripImageExtension(filename);
await API().local.storeImage(res.bodyBytes, storedName);
await OP.indexImageHash(
hash: hash,
storedName: storedName,
scope: scope,
);
final fallbackStoredName =
(scope.isNotEmpty) ? '$scope/$hash' : hash;
if (fallbackStoredName != storedName) {
await _deleteLocalImageQuietly(fallbackStoredName);
}
} else {
// If we already know a canonical local filename for this hash, use it
// and avoid creating an additional hash-named duplicate file.
if (!isPathHash) {
final indexed = await OP.lookupImageNameForHash(
hash,
scope: scope,
);
if (indexed != null && indexed.isNotEmpty) {
final existing =
await API().local.readImage(indexed, cacheSize: null);
if (existing != null) {
final fallbackStoredName =
(scope.isNotEmpty) ? '$scope/$hash' : hash;
if (fallbackStoredName != indexed) {
await _deleteLocalImageQuietly(fallbackStoredName);
}
return ImageData(
existing,
id: hash,
name: _stripImageExtension(indexed.split('/').last),
);
}
}
}
storedName =
(!isPathHash && scope.isNotEmpty) ? '$scope/$hash' : hash;
// fall back to hash-derived name (best-effort)
displayName = _stripImageExtension(storedName.split('/').last);
await API().local.storeImage(res.bodyBytes, storedName);
}
return ImageData(
(await API().local.readImage(storedName, cacheSize: null))!,
id: hash,
name: displayName,
);
} catch (e) {
debugPrint("failed to load webimg: " + e.toString());
}
}
}
return RequestAndParser(rd: rd, parser: parser);
}