PowerToys/Plugins/Wox.Plugin.WebSearch/SuggestionSources/Baidu.cs

66 lines
2.0 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
2014-12-21 22:03:03 +08:00
using Wox.Infrastructure.Http;
using Wox.Infrastructure.Logger;
namespace Wox.Plugin.WebSearch.SuggestionSources
{
public class Baidu : SuggestionSource
{
private readonly Regex _reg = new Regex("window.baidu.sug\\((.*)\\)");
public override async Task<List<string>> Suggestions(string query)
{
string result;
try
{
const string api = "http://suggestion.baidu.com/su?json=1&wd=";
2016-06-19 23:18:43 +08:00
result = await Http.Get(api + Uri.EscapeUriString(query), "GB2312");
}
catch (WebException e)
{
2017-01-24 08:24:20 +08:00
Log.Exception("|Baidu.Suggestions|Can't get suggestion from baidu", e);
return new List<string>();
}
2014-12-21 22:03:03 +08:00
if (string.IsNullOrEmpty(result)) return new List<string>();
Match match = _reg.Match(result);
2014-12-21 22:03:03 +08:00
if (match.Success)
{
JContainer json;
2014-12-21 22:03:03 +08:00
try
{
json = JsonConvert.DeserializeObject(match.Groups[1].Value) as JContainer;
2014-12-21 22:03:03 +08:00
}
catch (JsonSerializationException e)
{
2017-01-24 08:24:20 +08:00
Log.Exception("|Baidu.Suggestions|can't parse suggestions", e);
return new List<string>();
}
2014-12-21 22:03:03 +08:00
if (json != null)
{
2014-12-21 22:03:03 +08:00
var results = json["s"] as JArray;
if (results != null)
{
2014-12-21 22:03:03 +08:00
return results.OfType<JValue>().Select(o => o.Value).OfType<string>().ToList();
}
}
}
2014-12-21 22:03:03 +08:00
return new List<string>();
}
public override string ToString()
{
return "Baidu";
}
}
}