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

59 lines
1.7 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Infrastructure.Http;
using Flow.Launcher.Infrastructure.Logger;
using System.Net.Http;
2021-01-07 03:09:08 +00:00
using System.Threading;
using System.Text.Json;
2020-12-30 11:09:52 +00:00
using System.IO;
2020-04-21 09:12:17 +00:00
namespace Flow.Launcher.Plugin.WebSearch.SuggestionSources
{
public class Google : SuggestionSource
{
2021-01-07 03:09:08 +00:00
public override async Task<List<string>> Suggestions(string query, CancellationToken token)
{
2021-01-07 13:54:09 +00:00
JsonDocument json;
try
{
const string api = "https://www.google.com/complete/search?output=chrome&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)).ConfigureAwait(false);
2021-01-17 08:05:28 +00:00
if (resultStream.Length == 0)
return new List<string>();
2021-01-07 13:54:09 +00:00
json = await JsonDocument.ParseAsync(resultStream);
}
catch (TaskCanceledException)
{
return null;
}
catch (HttpRequestException e)
{
2017-01-24 00:24:20 +00:00
Log.Exception("|Google.Suggestions|Can't get suggestion from google", e);
return new List<string>();
}
catch (JsonException e)
{
Log.Exception("|Google.Suggestions|can't parse suggestions", e);
return new List<string>();
}
var results = json?.RootElement.EnumerateArray().ElementAt(1);
return results?.EnumerateArray().Select(o => o.GetString()).ToList() ?? new List<string>();
}
public override string ToString()
{
return "Google";
}
}
}