Flow.Launcher/Plugins/Flow.Launcher.Plugin.WebSearch/SuggestionSources/Bing.cs

54 lines
1.8 KiB
C#
Raw Normal View History

2025-04-02 10:26:22 +00:00
using System;
2020-12-30 12:24:01 +00:00
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
using System.Linq;
2021-01-07 03:09:08 +00:00
using System.Threading;
2020-12-30 12:24:01 +00:00
namespace Flow.Launcher.Plugin.WebSearch.SuggestionSources
{
2025-04-02 10:26:22 +00:00
public class Bing : SuggestionSource
2020-12-30 12:24:01 +00:00
{
2025-04-13 09:59:39 +00:00
private static readonly string ClassName = nameof(Bing);
public override async Task<List<string>> SuggestionsAsync(string query, CancellationToken token)
2020-12-30 12:24:01 +00:00
{
try
{
const string api = "https://api.bing.com/qsonhs.aspx?q=";
2025-04-02 10:26:22 +00:00
await using var resultStream = await Main._context.API.HttpGetStreamAsync(api + Uri.EscapeDataString(query), token).ConfigureAwait(false);
2021-02-16 02:50:48 +00:00
using var json = (await JsonDocument.ParseAsync(resultStream, cancellationToken: token));
var root = json.RootElement.GetProperty("AS");
if (root.GetProperty("FullResults").GetInt32() == 0)
return new List<string>();
return root.GetProperty("Results")
.EnumerateArray()
.SelectMany(r => r.GetProperty("Suggests")
.EnumerateArray()
.Select(s => s.GetProperty("Txt").GetString()))
.ToList();
2020-12-30 12:24:01 +00:00
}
catch (Exception e) when (e is HttpRequestException or { InnerException: TimeoutException })
{
2025-04-13 09:59:39 +00:00
Main._context.API.LogException(ClassName, "Can't get suggestion from Bing", e);
return null;
}
2020-12-30 12:24:01 +00:00
catch (JsonException e)
{
2025-04-13 09:59:39 +00:00
Main._context.API.LogException(ClassName, "Can't parse suggestions", e);
2020-12-30 12:24:01 +00:00
return new List<string>();
}
2020-12-30 12:24:01 +00:00
}
public override string ToString()
{
return "Bing";
}
}
}