private static string BuildImageQuery(string query, BraveImageSize size, BraveImageType type, BraveImageLayout layout, BraveImageColor color, BraveImageLicense license) { string url = $"images?q={Uri.EscapeDataString(query)}"; // Doesn't seem to work via query strings /* * if (level != SafeSearchLevel.Moderate) * url += $"&safesearch={level.ToString().ToLowerInvariant()}"; * * if (!string.IsNullOrEmpty(country)) * url += $"&country={country}"; */ if (size != BraveImageSize.All) { url += $"&size={size}"; } if (type != BraveImageType.All) { url += $"&_type={type}"; } if (layout != BraveImageLayout.All) { url += $"&layout={layout}"; } if (color != BraveImageColor.All) { url += $"&color={color}"; } if (license != BraveImageLicense.All) { url += $"&license={license}"; } return(url); }
/// <summary> /// Gets images from Brave Search. /// </summary> /// <remarks>This method returns at most 150 image results (unless Brave changes something in their API).</remarks> /// <param name="query">The search query.</param> /// <param name="safeSearch">The safe search level.</param> /// <param name="country">The country. <see cref="BraveCountries"/> contains the countries that can be used here.</param> /// <param name="size">The image size.</param> /// <param name="type">The image type.</param> /// <param name="layout">The image layout.</param> /// <param name="color">The image color.</param> /// <param name="license">The image license.</param> /// <returns>A task representing the asynchronous operation. The result contains an <see cref="IEnumerable{T}"/> of <see cref="BraveImageResult"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="query"/> is null or empty.</exception> /// <exception cref="GScraperException">An error occurred during the scraping process.</exception> public async Task <IEnumerable <BraveImageResult> > GetImagesAsync(string query, SafeSearchLevel safeSearch = SafeSearchLevel.Moderate, string?country = null, BraveImageSize size = BraveImageSize.All, BraveImageType type = BraveImageType.All, BraveImageLayout layout = BraveImageLayout.All, BraveImageColor color = BraveImageColor.All, BraveImageLicense license = BraveImageLicense.All) { GScraperGuards.NotNull(query, nameof(query)); byte[] bytes; using (var request = new HttpRequestMessage()) { string cookie = $"safesearch={safeSearch.ToString().ToLowerInvariant()}"; if (!string.IsNullOrEmpty(country)) { cookie += $"; country={country}"; } request.Method = HttpMethod.Get; request.RequestUri = new Uri(BuildImageQuery(query, size, type, layout, color, license), UriKind.Relative); request.Headers.Add("cookie", cookie); var response = await _httpClient.SendAsync(request).ConfigureAwait(false); response.EnsureSuccessStatusCode(); bytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); } var document = JsonDocument.Parse(bytes); var results = document.RootElement.GetPropertyOrDefault("results"); return(EnumerateResults(results)); }