Skip to content

Commit

Permalink
Add youdao plugin.
Browse files Browse the repository at this point in the history
  • Loading branch information
qianlifeng committed Mar 12, 2014
1 parent fe7afe3 commit 5d2ce27
Show file tree
Hide file tree
Showing 9 changed files with 479 additions and 3 deletions.
63 changes: 63 additions & 0 deletions .gitattributes
@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto

###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp

###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary

###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary

###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
135 changes: 135 additions & 0 deletions Plugins/Wox.Plugin.Youdao/HttpRequest.cs
@@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

//From:http://blog.csdn.net/zhoufoxcn/article/details/6404236
namespace Wox.Plugin.Fanyi
{
/// <summary>
/// 有关HTTP请求的辅助类
/// </summary>
public class HttpRequest
{
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
/// <summary>
/// 创建GET方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.UserAgent = DefaultUserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
}
/// <summary>
/// 创建POST方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
else
{
request.UserAgent = DefaultUserAgent;
}

if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
//如果需要POST数据
if (!(parameters == null || parameters.Count == 0))
{
StringBuilder buffer = new StringBuilder();
int i = 0;
foreach (string key in parameters.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
}
i++;
}
byte[] data = requestEncoding.GetBytes(buffer.ToString());
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
return request.GetResponse() as HttpWebResponse;
}

private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
}
}
Binary file added Plugins/Wox.Plugin.Youdao/Images/youdao.ico
Binary file not shown.
128 changes: 128 additions & 0 deletions Plugins/Wox.Plugin.Youdao/Main.cs
@@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Wox.Plugin.Fanyi;

namespace Wox.Plugin.Youdao
{
public class TranslateResult
{
public int errorCode { get; set; }
public List<string> translation { get; set; }
public BasicTranslation basic { get; set; }
public List<WebTranslation> web { get; set; }
}

// 有道词典-基本词典
public class BasicTranslation
{
public string phonetic { get; set; }
public List<string> explains { get; set; }
}

public class WebTranslation
{
public string key { get; set; }
public List<string> value { get; set; }
}

public class Main : IPlugin
{
private string translateURL = "http://fanyi.youdao.com/openapi.do?keyfrom=WoxLauncher&key=1247918016&type=data&doctype=json&version=1.1&q=";

public List<Result> Query(Query query)
{
List<Result> results = new List<Result>();
if (query.ActionParameters.Count == 0)
{
results.Add(new Result()
{
Title = "Start to translate between Chinese and English",
SubTitle = "Powered by youdao api",
IcoPath = "Images\\youdao.ico"
});
return results;
}

HttpWebResponse response = HttpRequest.CreatePostHttpResponse(translateURL + query.GetAllRemainingParameter(), null, null, null, Encoding.UTF8, null);
Stream s = response.GetResponseStream();
if (s != null)
{
StreamReader reader = new StreamReader(s, Encoding.UTF8);
string json = reader.ReadToEnd();
TranslateResult o = JsonConvert.DeserializeObject<TranslateResult>(json);
if (o.errorCode == 0)
{
if (o.basic != null && o.basic.phonetic != null)
{
results.Add(new Result()
{
Title = o.basic.phonetic,
SubTitle = string.Join(",", o.basic.explains.ToArray()),
IcoPath = "Images\\youdao.ico",
});
}
foreach (string t in o.translation)
{
results.Add(new Result()
{
Title = t,
IcoPath = "Images\\youdao.ico",
});
}
if (o.web != null)
{
foreach (WebTranslation t in o.web)
{
results.Add(new Result()
{
Title = t.key,
SubTitle = string.Join(",", t.value.ToArray()),
IcoPath = "Images\\youdao.ico",
});
}
}
}
else
{
string error = string.Empty;
switch (o.errorCode)
{
case 20:
error = "要翻译的文本过长";
break;

case 30:
error = "无法进行有效的翻译";
break;

case 40:
error = "不支持的语言类型";
break;

case 50:
error = "无效的key";
break;
}

results.Add(new Result()
{
Title = error,
IcoPath = "Images\\youdao.ico",
});
}
}

return results;
}

public void Init(PluginInitContext context)
{

}
}
}
36 changes: 36 additions & 0 deletions Plugins/Wox.Plugin.Youdao/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Wox.Plugin.Youdao")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Oracle Corporation")]
[assembly: AssemblyProduct("Wox.Plugin.Youdao")]
[assembly: AssemblyCopyright("Copyright © Oracle Corporation 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e42a24ab-7eff-46e8-ae37-f85bc08de1b8")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

0 comments on commit 5d2ce27

Please sign in to comment.