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

51 lines
1.6 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;
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
{
public override async Task<List<string>> Suggestions(string query)
{
2020-12-30 11:09:52 +00:00
Stream resultStream;
try
{
const string api = "https://www.google.com/complete/search?output=chrome&q=";
2020-12-30 11:09:52 +00:00
resultStream = await Http.GetStreamAsync(api + Uri.EscapeUriString(query)).ConfigureAwait(false);
}
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>();
}
2020-12-30 11:09:52 +00:00
if (resultStream.Length == 0) return new List<string>();
JsonDocument json;
try
{
2020-12-30 11:09:52 +00:00
json = await JsonDocument.ParseAsync(resultStream);
}
catch (JsonException e)
{
2017-01-24 00:24:20 +00:00
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";
}
}
}