Add youdao plugin.

This commit is contained in:
qianlifeng 2014-03-12 09:16:22 +08:00
parent fe7afe3dec
commit 5d2ce27ea8
9 changed files with 479 additions and 3 deletions

63
.gitattributes vendored Normal file
View File

@ -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

View File

@ -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 not shown.

After

Width:  |  Height:  |  Size: 515 KiB

View File

@ -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)
{
}
}
}

View File

@ -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")]

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AE02E18E-2134-472B-9282-32CDE36B5F0C}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Wox.Plugin.Youdao</RootNamespace>
<AssemblyName>Wox.Plugin.Youdao</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\Wox.Test\bin\Debug\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="HttpRequest.cs" />
<Compile Include="Main.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="plugin.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Content Include="Images\youdao.ico" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj">
<Project>{8451ECDD-2EA4-4966-BB0A-7BBC40138E80}</Project>
<Name>Wox.Plugin</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>xcopy /Y /E $(TargetDir)*.* $(SolutionDir)Wox\bin\Debug\Plugins\$(ProjectName)\
xcopy /Y /E $(ProjectDir)Images $(SolutionDir)Wox\bin\Debug\Plugins\$(ProjectName)\Images\</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,11 @@
{
"ID":"095A6AE3A254432EBBD78F05A71D4981",
"ActionKeyword":"yd",
"Name":"Youdao Translator",
"Description":"Translate Chinese and English",
"Author":"qianlifeng",
"Version":"1.0",
"Language":"csharp",
"Website":"http://www.getwox.com",
"ExecuteFileName":"Wox.Plugin.Youdao.dll"
}

35
Wox.sln
View File

@ -1,8 +1,6 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30110.0
MinimumVisualStudioVersion = 10.0.40219.1
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wox.Test", "Wox.Test\Wox.Test.csproj", "{FF742965-9A80-41A5-B042-D6C7D3A21708}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wox.Plugin", "Wox.Plugin\Wox.Plugin.csproj", "{8451ECDD-2EA4-4966-BB0A-7BBC40138E80}"
@ -29,6 +27,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wox.Plugin.Clipboard", "Plu
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wox.Plugin.PluginManagement", "Wox.Plugin\Wox.Plugin.PluginManagement\Wox.Plugin.PluginManagement.csproj", "{049490F0-ECD2-4148-9B39-2135EC346EBE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wox.Plugin.Youdao", "Plugins\Wox.Plugin.Youdao\Wox.Plugin.Youdao.csproj", "{AE02E18E-2134-472B-9282-32CDE36B5F0C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -406,6 +406,34 @@ Global
{049490F0-ECD2-4148-9B39-2135EC346EBE}.UnitTests|Win32.ActiveCfg = Release|Any CPU
{049490F0-ECD2-4148-9B39-2135EC346EBE}.UnitTests|x64.ActiveCfg = Release|Any CPU
{049490F0-ECD2-4148-9B39-2135EC346EBE}.UnitTests|x86.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Debug|Win32.ActiveCfg = Debug|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Debug|x64.ActiveCfg = Debug|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Debug|x86.ActiveCfg = Debug|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.EmbeddingTest|Any CPU.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.EmbeddingTest|Any CPU.Build.0 = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.EmbeddingTest|Mixed Platforms.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.EmbeddingTest|Mixed Platforms.Build.0 = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.EmbeddingTest|Win32.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.EmbeddingTest|x64.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.EmbeddingTest|x86.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Release|Any CPU.Build.0 = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Release|Win32.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Release|x64.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.Release|x86.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.UnitTests|Any CPU.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.UnitTests|Any CPU.Build.0 = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.UnitTests|Mixed Platforms.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.UnitTests|Mixed Platforms.Build.0 = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.UnitTests|Win32.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.UnitTests|x64.ActiveCfg = Release|Any CPU
{AE02E18E-2134-472B-9282-32CDE36B5F0C}.UnitTests|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -416,5 +444,6 @@ Global
{230AE83F-E92E-4E69-8355-426B305DA9C0} = {3A73F5A7-0335-40D8-BF7C-F20BE5D0BA87}
{8C14DC11-2737-4DCB-A121-5D7BDD57FEA2} = {3A73F5A7-0335-40D8-BF7C-F20BE5D0BA87}
{049490F0-ECD2-4148-9B39-2135EC346EBE} = {3A73F5A7-0335-40D8-BF7C-F20BE5D0BA87}
{AE02E18E-2134-472B-9282-32CDE36B5F0C} = {3A73F5A7-0335-40D8-BF7C-F20BE5D0BA87}
EndGlobalSection
EndGlobal

BIN
Wox/bin/Debug/Wox.exe Normal file

Binary file not shown.