Add manually check updates option

1. manually check updates
2. refactoring get http request to use async
3. remove some generic exception catch
4. remove unused code
This commit is contained in:
bao-qian
2016-05-09 02:32:47 +01:00
parent 373da78b7b
commit 6ac33b0568
13 changed files with 209 additions and 147 deletions

View File

@@ -85,10 +85,10 @@ namespace Wox.Plugin.WebSearch
if (_settings.EnableWebSearchSuggestion) if (_settings.EnableWebSearchSuggestion)
{ {
const int waittime = 300; const int waittime = 300;
var task = Task.Run(() => var task = Task.Run(async () =>
{ {
results.AddRange(ResultsFromSuggestions(keyword, subtitle, webSearch)); var suggestions = await Suggestions(keyword, subtitle, webSearch);
results.AddRange(suggestions);
}, _updateToken); }, _updateToken);
if (!task.Wait(waittime)) if (!task.Wait(waittime))
@@ -102,12 +102,12 @@ namespace Wox.Plugin.WebSearch
} }
} }
private IEnumerable<Result> ResultsFromSuggestions(string keyword, string subtitle, WebSearch webSearch) private async Task<IEnumerable<Result>> Suggestions(string keyword, string subtitle, WebSearch webSearch)
{ {
var source = SuggestionSource.GetSuggestionSource(_settings.WebSearchSuggestionSource, Context); var source = SuggestionSource.GetSuggestionSource(_settings.WebSearchSuggestionSource, Context);
var suggestions = source?.GetSuggestions(keyword); if (source != null)
if (suggestions != null)
{ {
var suggestions = await source.GetSuggestions(keyword);
var resultsFromSuggestion = suggestions.Select(o => new Result var resultsFromSuggestion = suggestions.Select(o => new Result
{ {
Title = o, Title = o,

View File

@@ -2,9 +2,11 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Wox.Infrastructure.Http; using Wox.Infrastructure.Http;
using Wox.Infrastructure.Logger;
namespace Wox.Plugin.WebSearch.SuggestionSources namespace Wox.Plugin.WebSearch.SuggestionSources
{ {
@@ -14,20 +16,24 @@ namespace Wox.Plugin.WebSearch.SuggestionSources
Regex reg = new Regex("window.baidu.sug\\((.*)\\)"); Regex reg = new Regex("window.baidu.sug\\((.*)\\)");
public override List<string> GetSuggestions(string query) public override async Task<List<string>> GetSuggestions(string query)
{ {
var result = HttpRequest.Get("http://suggestion.baidu.com/su?json=1&wd=" + Uri.EscapeUriString(query), Proxy, "GB2312"); var result = await HttpRequest.Get("http://suggestion.baidu.com/su?json=1&wd=" + Uri.EscapeUriString(query), Proxy, "GB2312");
if (string.IsNullOrEmpty(result)) return new List<string>(); if (string.IsNullOrEmpty(result)) return new List<string>();
Match match = reg.Match(result); Match match = reg.Match(result);
if (match.Success) if (match.Success)
{ {
JContainer json = null; JContainer json;
try try
{ {
json = JsonConvert.DeserializeObject(match.Groups[1].Value) as JContainer; json = JsonConvert.DeserializeObject(match.Groups[1].Value) as JContainer;
} }
catch { } catch (JsonSerializationException e)
{
Log.Error(e);
return new List<string>();
}
if (json != null) if (json != null)
{ {

View File

@@ -1,34 +1,39 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Wox.Infrastructure.Http; using Wox.Infrastructure.Http;
using Wox.Infrastructure.Logger;
namespace Wox.Plugin.WebSearch.SuggestionSources namespace Wox.Plugin.WebSearch.SuggestionSources
{ {
public class Google : SuggestionSource public class Google : SuggestionSource
{ {
public override string Domain { get; set; } = "www.google.com"; public override string Domain { get; set; } = "www.google.com";
public override List<string> GetSuggestions(string query) public override async Task<List<string>> GetSuggestions(string query)
{ {
var result = HttpRequest.Get("https://www.google.com/complete/search?output=chrome&q=" + Uri.EscapeUriString(query), Proxy); var result = await HttpRequest.Get("https://www.google.com/complete/search?output=chrome&q=" + Uri.EscapeUriString(query), Proxy);
if (string.IsNullOrEmpty(result)) return new List<string>(); if (string.IsNullOrEmpty(result)) return new List<string>();
JContainer json;
try try
{ {
JContainer json = JsonConvert.DeserializeObject(result) as JContainer; json = JsonConvert.DeserializeObject(result) as JContainer;
if (json != null) }
catch (JsonSerializationException e)
{
Log.Error(e);
return new List<string>();
}
if (json != null)
{
var results = json[1] as JContainer;
if (results != null)
{ {
var results = json[1] as JContainer; return results.OfType<JValue>().Select(o => o.Value).OfType<string>().ToList();
if (results != null)
{
return results.OfType<JValue>().Select(o => o.Value).OfType<string>().ToList();
}
} }
} }
catch { }
return new List<string>(); return new List<string>();
} }

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
namespace Wox.Plugin.WebSearch.SuggestionSources namespace Wox.Plugin.WebSearch.SuggestionSources
{ {
@@ -12,7 +13,7 @@ namespace Wox.Plugin.WebSearch.SuggestionSources
Proxy = httpProxy; Proxy = httpProxy;
} }
public abstract List<string> GetSuggestions(string query); public abstract Task<List<string>> GetSuggestions(string query);
public static SuggestionSource GetSuggestionSource(string name, PluginInitContext context) public static SuggestionSource GetSuggestionSource(string name, PluginInitContext context)
{ {

View File

@@ -1,9 +0,0 @@
namespace Wox.Core
{
public static class APIServer
{
private static string BaseAPIURL = "http://api.getwox.com";
public static string ErrorReportURL = BaseAPIURL + "/error/";
public static string LastestReleaseURL = BaseAPIURL + "/release/latest/";
}
}

View File

@@ -64,7 +64,6 @@
<Compile Include="..\SolutionAssemblyInfo.cs"> <Compile Include="..\SolutionAssemblyInfo.cs">
<Link>Properties\SolutionAssemblyInfo.cs</Link> <Link>Properties\SolutionAssemblyInfo.cs</Link>
</Compile> </Compile>
<Compile Include="APIServer.cs" />
<Compile Include="Plugin\ExecutablePlugin.cs" /> <Compile Include="Plugin\ExecutablePlugin.cs" />
<Compile Include="Plugin\PluginsLoader.cs" /> <Compile Include="Plugin\PluginsLoader.cs" />
<Compile Include="UserSettings\HttpProxy.cs" /> <Compile Include="UserSettings\HttpProxy.cs" />

View File

@@ -1,120 +1,79 @@
using System.IO; using System;
using System.IO;
using System.Net; using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Wox.Infrastructure.Logger; using Wox.Infrastructure.Logger;
using Wox.Plugin; using Wox.Plugin;
namespace Wox.Infrastructure.Http namespace Wox.Infrastructure.Http
{ {
public class HttpRequest public static class HttpRequest
{ {
public static string Get(string url, IHttpProxy proxy, string encoding = "UTF-8") private static WebProxy GetWebProxy(IHttpProxy proxy)
{
return Get(url, encoding, proxy);
}
public static WebProxy GetWebProxy(IHttpProxy proxy)
{ {
if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server)) if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
{ {
if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password)) if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
{ {
return new WebProxy(proxy.Server, proxy.Port); var webProxy = new WebProxy(proxy.Server, proxy.Port);
} return webProxy;
return new WebProxy(proxy.Server, proxy.Port)
{
Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
};
}
return null;
}
private static string Get(string url, string encoding, IHttpProxy proxy)
{
if (string.IsNullOrEmpty(url)) return string.Empty;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.Timeout = 10 * 1000;
request.Proxy = GetWebProxy(proxy);
try
{
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{
return reader.ReadToEnd();
}
}
}
}
catch (System.Exception e)
{
Log.Error(e);
return string.Empty;
}
return string.Empty;
}
public static string Post(string url, string jsonData, IHttpProxy proxy)
{
if (string.IsNullOrEmpty(url)) return string.Empty;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/json";
request.Timeout = 10 * 1000;
if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
{
if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port);
} }
else else
{ {
request.Proxy = new WebProxy(proxy.Server, proxy.Port) var webProxy = new WebProxy(proxy.Server, proxy.Port)
{ {
Credentials = new NetworkCredential(proxy.UserName, proxy.Password) Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
}; };
return webProxy;
} }
} }
using (var streamWriter = new StreamWriter(request.GetRequestStream())) else
{ {
streamWriter.Write(jsonData); return null;
streamWriter.Flush();
streamWriter.Close();
} }
}
public static async Task<string> Get([NotNull] string url, IHttpProxy proxy, string encoding = "UTF-8")
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "GET";
request.Timeout = 10 * 1000;
request.Proxy = GetWebProxy(proxy);
request.UserAgent = @"Mozilla/5.0 (Trident/7.0; rv:11.0) like Gecko";
HttpWebResponse response;
try try
{ {
HttpWebResponse response = request.GetResponse() as HttpWebResponse; response = await request.GetResponseAsync() as HttpWebResponse;
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{
return reader.ReadToEnd();
}
}
}
} }
catch (System.Exception e) catch (WebException e)
{ {
Log.Error(e); Log.Error(e);
return string.Empty; return string.Empty;
} }
if (response != null)
return string.Empty; {
var stream = response.GetResponseStream();
if (stream != null)
{
using (var reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{
return await reader.ReadToEndAsync();
}
}
else
{
return string.Empty;
}
}
else
{
return string.Empty;
}
} }
} }
} }

View File

@@ -57,6 +57,7 @@
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Drawing" /> <Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml" /> <Reference Include="System.Xaml" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="WindowsBase" /> <Reference Include="WindowsBase" />

View File

@@ -64,7 +64,15 @@ namespace Wox
} }
catch (Exception exception) catch (Exception exception)
{ {
Log.Error(exception); const string info = "Update.exe not found, not a Squirrel-installed app?";
if (exception.Message == info)
{
Log.Warn("info");
}
else
{
throw;
}
} }
} }

View File

@@ -78,6 +78,9 @@
<system:String x:Key="about">About</system:String> <system:String x:Key="about">About</system:String>
<system:String x:Key="website">Website</system:String> <system:String x:Key="website">Website</system:String>
<system:String x:Key="version">Version</system:String> <system:String x:Key="version">Version</system:String>
<system:String x:Key="checkUpdates">Check Updates</system:String>
<system:String x:Key="newVersionTips">New Version {0} avaiable, please restart</system:String>
<system:String x:Key="releaseNotes">Release Notes:</system:String>
<system:String x:Key="about_activate_times">You have activated Wox {0} times</system:String> <system:String x:Key="about_activate_times">You have activated Wox {0} times</system:String>
<!--Action Keyword Setting Dialog--> <!--Action Keyword Setting Dialog-->

View File

@@ -340,27 +340,42 @@
</Style> </Style>
</Grid.Resources> </Grid.Resources>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="80" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition /> <ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="{DynamicResource website}" /> <TextBlock x:Name="ActivatedTimes" Grid.Row="0" Grid.ColumnSpan="3"
<TextBlock Grid.Column="1" Grid.Row="0" HorizontalAlignment="Left" Cursor="Hand"
MouseUp="tbWebsite_MouseUp" x:Name="tbWebsite" Foreground="Blue"
Text="http://www.getwox.com" />
<TextBlock Grid.Column="0" Grid.Row="1" Text="{DynamicResource version}" />
<StackPanel Grid.Column="1" Grid.Row="1" Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" x:Name="tbVersion" Text="1.0.0" />
</StackPanel>
<TextBlock x:Name="tbActivatedTimes" Grid.Row="2" Grid.ColumnSpan="2"
Text="{DynamicResource about_activate_times}" /> Text="{DynamicResource about_activate_times}" />
<TextBlock Grid.Column="0" Grid.Row="1" Text="{DynamicResource website}" />
<TextBlock Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" >
<Hyperlink NavigateUri="https://github.com/Wox-launcher/Wox" RequestNavigate="OnRequestNavigate">
https://github.com/Wox-launcher/Wox
</Hyperlink>
</TextBlock>
<TextBlock Grid.Column="0" Grid.Row="2" Text="{DynamicResource version}" />
<TextBlock Grid.Column="1" Grid.Row="2" HorizontalAlignment="Left" x:Name="tbVersion" Text="1.0.0" />
<TextBlock Grid.Column="0" Grid.Row="3" Text="{DynamicResource releaseNotes}"></TextBlock>
<TextBlock Grid.Column="1" Grid.Row="3" HorizontalAlignment="Left" >
<Hyperlink NavigateUri="https://github.com/Wox-launcher/Wox/releases/latest" RequestNavigate="OnRequestNavigate">
https://github.com/Wox-launcher/Wox/releases/latest
</Hyperlink>
</TextBlock>
<Button Grid.Column="0" Grid.Row="4" Content="{DynamicResource checkUpdates}" HorizontalAlignment="Left" Margin="10 10 10 10"
Click="OnCheckUpdates"/>
<TextBlock Grid.Column="1" Grid.Row="4" Name="NewVersionTips" HorizontalAlignment="Left" Text="{DynamicResource newVersionTips}" Visibility="Hidden"/>
</Grid> </Grid>
</TabItem> </TabItem>
</TabControl> </TabControl>

View File

@@ -4,6 +4,8 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Data; using System.Windows.Data;
@@ -11,16 +13,21 @@ using System.Windows.Forms;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Win32; using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NHotkey; using NHotkey;
using NHotkey.Wpf; using NHotkey.Wpf;
using Squirrel;
using Wox.Core.Plugin; using Wox.Core.Plugin;
using Wox.Core.Resource; using Wox.Core.Resource;
using Wox.Core.Updater;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Helper; using Wox.Helper;
using Wox.Infrastructure.Hotkey; using Wox.Infrastructure.Hotkey;
using Wox.Infrastructure.Http;
using Wox.Infrastructure.Image; using Wox.Infrastructure.Image;
using Wox.Infrastructure.Logger;
using Wox.Plugin; using Wox.Plugin;
using Wox.ViewModel; using Wox.ViewModel;
using Application = System.Windows.Forms.Application; using Application = System.Windows.Forms.Application;
@@ -56,7 +63,7 @@ namespace Wox
_settings.ProxyEnabled = ToggleProxy.IsChecked ?? false; _settings.ProxyEnabled = ToggleProxy.IsChecked ?? false;
} }
private void Setting_Loaded(object sender, RoutedEventArgs ev) private async void Setting_Loaded(object sender, RoutedEventArgs ev)
{ {
#region General #region General
cbHideWhenDeactive.Checked += (o, e) => cbHideWhenDeactive.Checked += (o, e) =>
@@ -136,11 +143,10 @@ namespace Wox
#endregion #endregion
#region About #region About
string activateTimes = string.Format(
tbVersion.Text = UpdaterManager.Instance.CurrentVersion.ToString(); InternationalizationManager.Instance.GetTranslation("about_activate_times"), _settings.ActivateTimes);
string activateTimes = string.Format(InternationalizationManager.Instance.GetTranslation("about_activate_times"), ActivatedTimes.Text = activateTimes;
_settings.ActivateTimes); tbVersion.Text = Infrastructure.Wox.Version;
tbActivatedTimes.Text = activateTimes;
#endregion #endregion
@@ -806,7 +812,7 @@ namespace Wox
private void tbWebsite_MouseUp(object sender, MouseButtonEventArgs e) private void tbWebsite_MouseUp(object sender, MouseButtonEventArgs e)
{ {
Process.Start("http://www.getwox.com"); Process.Start(Infrastructure.Wox.Github);
} }
#endregion #endregion
@@ -820,5 +826,76 @@ namespace Wox
} }
} }
private async void OnCheckUpdates(object sender, RoutedEventArgs e)
{
try
{
var version = await NewVersion();
if (!string.IsNullOrEmpty(version))
{
var newVersion = NumericVersion(version);
var oldVersion = NumericVersion(Infrastructure.Wox.Version);
if (newVersion > oldVersion)
{
NewVersionTips.Text = string.Format(NewVersionTips.Text, version);
NewVersionTips.Visibility = Visibility.Visible;
using (var updater = await UpdateManager.GitHubUpdateManager(Infrastructure.Wox.Github, prerelease: true))
{
// todo 5/9 the return value of UpdateApp() is NULL, fucking useless!
await updater.UpdateApp();
}
}
}
}
catch (Exception ex)
{
Log.Error(ex);
}
}
private async Task<string> NewVersion()
{
const string githubAPI = @"https://api.github.com/repos/wox-launcher/wox/releases/latest";
var response = await HttpRequest.Get(githubAPI, HttpProxy.Instance);
if (!string.IsNullOrEmpty(response))
{
JContainer json;
try
{
json = (JContainer) JsonConvert.DeserializeObject(response);
}
catch (JsonSerializationException e)
{
Log.Error(e);
return string.Empty;
}
var version = json?["tag_name"]?.ToString();
if (!string.IsNullOrEmpty(version))
{
return version;
}
else
{
return string.Empty;
}
}
else
{
return string.Empty;
}
}
private
int NumericVersion(string version)
{
var newVersion = version.Replace("v", ".").Replace(".", "").Replace("*", "");
return int.Parse(newVersion);
}
private void OnRequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
} }
} }

View File

@@ -215,10 +215,6 @@
<SubType>Designer</SubType> <SubType>Designer</SubType>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<Page Include="WoxUpdate.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Resource Include="Images\update.png"> <Resource Include="Images\update.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Resource> </Resource>
@@ -432,8 +428,9 @@
cd "$(TargetDir)Plugins" &amp; del /s /q Pinyin4Net.dll cd "$(TargetDir)Plugins" &amp; del /s /q Pinyin4Net.dll
cd "$(TargetDir)" &amp; del /s /q *.xml cd "$(TargetDir)" &amp; del /s /q *.xml
cd "$(TargetDir)Installer" &amp; del /s /q *
) )
</PostBuildEvent> </PostBuildEvent>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<PreBuildEvent> <PreBuildEvent>
@@ -446,7 +443,7 @@
</Target> </Target>
<Target Name="AfterBuild" Condition=" '$(Configuration)' == 'Release'"> <Target Name="AfterBuild" Condition=" '$(Configuration)' == 'Release'">
<GetAssemblyIdentity AssemblyFiles="$(TargetPath)"> <GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
<Output TaskParameter="Assemblies" ItemName="myAssemblyInfo"/> <Output TaskParameter="Assemblies" ItemName="myAssemblyInfo" />
</GetAssemblyIdentity> </GetAssemblyIdentity>
<Exec Command="nuget pack $(SolutionDir)Deploy\wox.nuspec -Version %(myAssemblyInfo.Version) -Properties Configuration=Release -OutputDirectory $(TargetDir) -BasePath $(TargetDir)" /> <Exec Command="nuget pack $(SolutionDir)Deploy\wox.nuspec -Version %(myAssemblyInfo.Version) -Properties Configuration=Release -OutputDirectory $(TargetDir) -BasePath $(TargetDir)" />
<Exec Command="squirrel --releasify $(TargetDir)Wox.%(myAssemblyInfo.Version).nupkg --releaseDir $(TargetDir)Installer --no-msi" /> <Exec Command="squirrel --releasify $(TargetDir)Wox.%(myAssemblyInfo.Version).nupkg --releaseDir $(TargetDir)Installer --no-msi" />