detectNSFWFromUrl method
Detects NSFW content from a URL.
Downloads the image from url and detects NSFW content.
Follows HTTP redirects. The timeout for the HTTP request is 10 seconds.
Throws NsfwDetectorException if the request times out or returns a non-200 status code.
Implementation
Future<NsfwResult?> detectNSFWFromUrl(Uri url) async {
if (_isClosed) throw StateError('NsfwDetector has been closed.');
final client = HttpClient();
client.connectionTimeout = const Duration(seconds: 10);
try {
final request = await client.getUrl(url);
final response = await request.close().timeout(
const Duration(seconds: 10),
onTimeout: () => throw TimeoutException('HTTP request timed out after 10 seconds.'),
);
if (response.statusCode != HttpStatus.ok) {
throw HttpException('HTTP request failed with status: ${response.statusCode}');
}
final bytes = await consolidateHttpClientResponseBytes(response);
return await detectNSFWFromBytes(bytes);
} catch (error, stackTrace) {
if (error is NsfwDetectorException) {
rethrow;
}
throw NsfwDetectorException(
'Failed to detect NSFW content from URL: $url',
cause: error,
stackTrace: stackTrace,
);
} finally {
client.close();
}
}