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)
{
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);
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 suggestions = source?.GetSuggestions(keyword);
if (suggestions != null)
if (source != null)
{
var suggestions = await source.GetSuggestions(keyword);
var resultsFromSuggestion = suggestions.Select(o => new Result
{
Title = o,

View file

@ -2,9 +2,11 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Wox.Infrastructure.Http;
using Wox.Infrastructure.Logger;
namespace Wox.Plugin.WebSearch.SuggestionSources
{
@ -14,20 +16,24 @@ namespace Wox.Plugin.WebSearch.SuggestionSources
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>();
Match match = reg.Match(result);
if (match.Success)
{
JContainer json = null;
JContainer json;
try
{
json = JsonConvert.DeserializeObject(match.Groups[1].Value) as JContainer;
}
catch { }
catch (JsonSerializationException e)
{
Log.Error(e);
return new List<string>();
}
if (json != null)
{

View file

@ -1,34 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Wox.Infrastructure.Http;
using Wox.Infrastructure.Logger;
namespace Wox.Plugin.WebSearch.SuggestionSources
{
public class Google : SuggestionSource
{
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>();
JContainer json;
try
{
JContainer json = JsonConvert.DeserializeObject(result) as JContainer;
if (json != null)
json = JsonConvert.DeserializeObject(result) as JContainer;
}
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;
if (results != null)
{
return results.OfType<JValue>().Select(o => o.Value).OfType<string>().ToList();
}
return results.OfType<JValue>().Select(o => o.Value).OfType<string>().ToList();
}
}
catch { }
return new List<string>();
}

View file

@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Wox.Plugin.WebSearch.SuggestionSources
{
@ -12,7 +13,7 @@ namespace Wox.Plugin.WebSearch.SuggestionSources
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)
{

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">
<Link>Properties\SolutionAssemblyInfo.cs</Link>
</Compile>
<Compile Include="APIServer.cs" />
<Compile Include="Plugin\ExecutablePlugin.cs" />
<Compile Include="Plugin\PluginsLoader.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.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Wox.Infrastructure.Logger;
using Wox.Plugin;
namespace Wox.Infrastructure.Http
{
public class HttpRequest
public static class HttpRequest
{
public static string Get(string url, IHttpProxy proxy, string encoding = "UTF-8")
{
return Get(url, encoding, proxy);
}
public static WebProxy GetWebProxy(IHttpProxy proxy)
private static WebProxy GetWebProxy(IHttpProxy proxy)
{
if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
{
if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
{
return new WebProxy(proxy.Server, proxy.Port);
}
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);
var webProxy = new WebProxy(proxy.Server, proxy.Port);
return webProxy;
}
else
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port)
var webProxy = new WebProxy(proxy.Server, proxy.Port)
{
Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
};
return webProxy;
}
}
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
else
{
streamWriter.Write(jsonData);
streamWriter.Flush();
streamWriter.Close();
return null;
}
}
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
{
HttpWebResponse response = request.GetResponse() 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();
}
}
}
response = await request.GetResponseAsync() as HttpWebResponse;
}
catch (System.Exception e)
catch (WebException e)
{
Log.Error(e);
return string.Empty;
}
return string.Empty;
if (response != null)
{
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.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />

View file

@ -64,7 +64,15 @@ namespace Wox
}
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="website">Website</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>
<!--Action Keyword Setting Dialog-->

View file

@ -340,27 +340,42 @@
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="{DynamicResource website}" />
<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"
<TextBlock x:Name="ActivatedTimes" Grid.Row="0" Grid.ColumnSpan="3"
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>
</TabItem>
</TabControl>

View file

@ -4,6 +4,8 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
@ -11,16 +13,21 @@ using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NHotkey;
using NHotkey.Wpf;
using Squirrel;
using Wox.Core.Plugin;
using Wox.Core.Resource;
using Wox.Core.Updater;
using Wox.Core.UserSettings;
using Wox.Helper;
using Wox.Infrastructure.Hotkey;
using Wox.Infrastructure.Http;
using Wox.Infrastructure.Image;
using Wox.Infrastructure.Logger;
using Wox.Plugin;
using Wox.ViewModel;
using Application = System.Windows.Forms.Application;
@ -56,7 +63,7 @@ namespace Wox
_settings.ProxyEnabled = ToggleProxy.IsChecked ?? false;
}
private void Setting_Loaded(object sender, RoutedEventArgs ev)
private async void Setting_Loaded(object sender, RoutedEventArgs ev)
{
#region General
cbHideWhenDeactive.Checked += (o, e) =>
@ -136,11 +143,10 @@ namespace Wox
#endregion
#region About
tbVersion.Text = UpdaterManager.Instance.CurrentVersion.ToString();
string activateTimes = string.Format(InternationalizationManager.Instance.GetTranslation("about_activate_times"),
_settings.ActivateTimes);
tbActivatedTimes.Text = activateTimes;
string activateTimes = string.Format(
InternationalizationManager.Instance.GetTranslation("about_activate_times"), _settings.ActivateTimes);
ActivatedTimes.Text = activateTimes;
tbVersion.Text = Infrastructure.Wox.Version;
#endregion
@ -806,7 +812,7 @@ namespace Wox
private void tbWebsite_MouseUp(object sender, MouseButtonEventArgs e)
{
Process.Start("http://www.getwox.com");
Process.Start(Infrastructure.Wox.Github);
}
#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>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<Page Include="WoxUpdate.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Resource Include="Images\update.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Resource>
@ -432,8 +428,9 @@
cd "$(TargetDir)Plugins" &amp; del /s /q Pinyin4Net.dll
cd "$(TargetDir)" &amp; del /s /q *.xml
cd "$(TargetDir)Installer" &amp; del /s /q *
)
</PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<PropertyGroup>
<PreBuildEvent>
@ -446,7 +443,7 @@
</Target>
<Target Name="AfterBuild" Condition=" '$(Configuration)' == 'Release'">
<GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
<Output TaskParameter="Assemblies" ItemName="myAssemblyInfo"/>
<Output TaskParameter="Assemblies" ItemName="myAssemblyInfo" />
</GetAssemblyIdentity>
<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" />