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

61 lines
2 KiB
C#
Raw Permalink Normal View History

2020-12-30 12:24:01 +00:00
using Flow.Launcher.Infrastructure.Http;
using Flow.Launcher.Infrastructure.Logger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
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
{
class Bing : SuggestionSource
{
2021-01-07 03:09:08 +00:00
public override async Task<List<string>> Suggestions(string query, CancellationToken token)
2020-12-30 12:24:01 +00:00
{
try
{
const string api = "https://api.bing.com/qsonhs.aspx?q=";
2021-01-17 08:05:28 +00:00
2021-01-07 13:54:09 +00:00
using var resultStream = await Http.GetStreamAsync(api + Uri.EscapeUriString(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();
2021-01-07 13:54:09 +00:00
2020-12-30 12:24:01 +00:00
}
catch (Exception e) when (e is HttpRequestException || e.InnerException is TimeoutException)
{
Log.Exception("|Baidu.Suggestions|Can't get suggestion from baidu", e);
return null;
}
2020-12-30 12:24:01 +00:00
catch (JsonException e)
{
Log.Exception("|Bing.Suggestions|can't parse suggestions", e);
return new List<string>();
}
2020-12-30 12:24:01 +00:00
}
public override string ToString()
{
return "Bing";
}
}
}