OSDN Git Service

ImgAzyobuziNetクラス内の OTWebClient に依存している箇所を HttpClient に置き換え
authorKimura Youichi <kim.upsilon@bucyou.net>
Mon, 21 Apr 2014 17:30:15 +0000 (02:30 +0900)
committerKimura Youichi <kim.upsilon@bucyou.net>
Sat, 26 Apr 2014 09:44:36 +0000 (18:44 +0900)
OpenTween.Tests/Thumbnail/Services/ImgAzyobuziNetTest.cs
OpenTween/Thumbnail/Services/ImgAzyobuziNet.cs
OpenTween/Tween.cs

index 7a04a47..4014709 100644 (file)
@@ -22,7 +22,7 @@
 using System;
 using System.Collections.Generic;
 using System.Linq;
-using System.Net;
+using System.Net.Http;
 using System.Reflection;
 using System.Runtime.InteropServices;
 using System.Text;
@@ -47,7 +47,7 @@ namespace OpenTween.Thumbnail.Services
                 : base(autoupdate: false)
             {
                 this.ApiHosts = apiHosts;
-                this.LoadRegex();
+                this.LoadRegexAsync().Wait();
             }
 
             public string GetApiBase()
@@ -55,42 +55,45 @@ namespace OpenTween.Thumbnail.Services
                 return this.ApiBase;
             }
 
-            protected override byte[] FetchRegex(string apiBase)
+            protected override Task<byte[]> FetchRegexAsync(string apiBase)
             {
-                if (apiBase == "http://down.example.com/api/")
-                    throw new WebException();
+                return Task.Run(() =>
+                {
+                    if (apiBase == "http://down.example.com/api/")
+                        throw new HttpRequestException();
 
-                if (apiBase == "http://error.example.com/api/")
-                    return Encoding.UTF8.GetBytes("{\"error\": {\"code\": 5001}}");
+                    if (apiBase == "http://error.example.com/api/")
+                        return Encoding.UTF8.GetBytes("{\"error\": {\"code\": 5001}}");
 
-                if (apiBase == "http://invalid.example.com/api/")
-                    return Encoding.UTF8.GetBytes("<<<INVALID JSON>>>");
+                    if (apiBase == "http://invalid.example.com/api/")
+                        return Encoding.UTF8.GetBytes("<<<INVALID JSON>>>");
 
-                return Encoding.UTF8.GetBytes("[{\"name\": \"hogehoge\", \"regex\": \"^https?://example.com/(.+)$\"}]");
+                    return Encoding.UTF8.GetBytes("[{\"name\": \"hogehoge\", \"regex\": \"^https?://example.com/(.+)$\"}]");
+                });
             }
         }
 
         [Fact]
-        public void HostFallbackTest()
+        public async Task HostFallbackTest()
         {
             var service = new TestImgAzyobuziNet(new[] { "http://avail1.example.com/api/", "http://avail2.example.com/api/" });
-            service.LoadRegex();
+            await service.LoadRegexAsync();
             Assert.Equal("http://avail1.example.com/api/", service.GetApiBase());
 
             service = new TestImgAzyobuziNet(new[] { "http://down.example.com/api/", "http://avail.example.com/api/" });
-            service.LoadRegex();
+            await service.LoadRegexAsync();
             Assert.Equal("http://avail.example.com/api/", service.GetApiBase());
 
             service = new TestImgAzyobuziNet(new[] { "http://error.example.com/api/", "http://avail.example.com/api/" });
-            service.LoadRegex();
+            await service.LoadRegexAsync();
             Assert.Equal("http://avail.example.com/api/", service.GetApiBase());
 
             service = new TestImgAzyobuziNet(new[] { "http://invalid.example.com/api/", "http://avail.example.com/api/" });
-            service.LoadRegex();
+            await service.LoadRegexAsync();
             Assert.Equal("http://avail.example.com/api/", service.GetApiBase());
 
             service = new TestImgAzyobuziNet(new[] { "http://down.example.com/api/" });
-            service.LoadRegex();
+            await service.LoadRegexAsync();
             Assert.Null(service.GetApiBase());
         }
 
@@ -99,7 +102,7 @@ namespace OpenTween.Thumbnail.Services
         {
             var service = new TestImgAzyobuziNet(new[] { "http://down.example.com/api/" });
 
-            service.LoadRegex();
+            await service.LoadRegexAsync();
             Assert.Null(service.GetApiBase());
 
             var thumbinfo = await service.GetThumbnailInfoAsync("http://example.com/abcd", null, CancellationToken.None);
index e60e40e..39ef490 100644 (file)
@@ -22,7 +22,6 @@
 using System;
 using System.Collections.Generic;
 using System.Linq;
-using System.Net;
 using System.Net.Http;
 using System.Runtime.Serialization.Json;
 using System.Xml;
@@ -65,7 +64,7 @@ namespace OpenTween.Thumbnail.Services
 
         public ImgAzyobuziNet(HttpClient http, bool autoupdate)
         {
-            this.UpdateTimer = new Timer(_ => this.LoadRegex());
+            this.UpdateTimer = new Timer(async _ => await this.LoadRegexAsync());
             this.AutoUpdate = autoupdate;
 
             this.Enabled = true;
@@ -109,13 +108,15 @@ namespace OpenTween.Thumbnail.Services
             this.UpdateTimer.Change(Timeout.Infinite, Timeout.Infinite);
         }
 
-        public void LoadRegex()
+        public async Task LoadRegexAsync()
         {
             foreach (var host in this.ApiHosts)
             {
                 try
                 {
-                    var result = this.LoadRegex(host);
+                    var result = await this.LoadRegexAsync(host)
+                        .ConfigureAwait(false);
+
                     if (result) return;
                 }
                 catch (Exception)
@@ -134,11 +135,14 @@ namespace OpenTween.Thumbnail.Services
             }
         }
 
-        public bool LoadRegex(string apiBase)
+        public async Task<bool> LoadRegexAsync(string apiBase)
         {
             try
             {
-                using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(this.FetchRegex(apiBase), XmlDictionaryReaderQuotas.Max))
+                var jsonBytes = await this.FetchRegexAsync(apiBase)
+                    .ConfigureAwait(false);
+
+                using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
                 {
                     var xElm = XElement.Load(jsonReader);
 
@@ -157,17 +161,23 @@ namespace OpenTween.Thumbnail.Services
 
                 return true;
             }
-            catch (WebException) { } // サーバーが2xx以外のステータスコードを返した場合
+            catch (HttpRequestException) { } // サーバーが2xx以外のステータスコードを返した場合
+            catch (OperationCanceledException) { } // リクエストがタイムアウトした場合
             catch (XmlException) { } // サーバーが不正なJSONを返した場合
 
             return false;
         }
 
-        protected virtual byte[] FetchRegex(string apiBase)
+        protected virtual async Task<byte[]> FetchRegexAsync(string apiBase)
         {
-            using (var client = new OTWebClient() { Timeout = 1000 })
+            using (var cts = new CancellationTokenSource(millisecondsDelay: 1000))
+            using (var response = await this.http.GetAsync(apiBase + "regex.json", cts.Token)
+                .ConfigureAwait(false))
             {
-                return client.DownloadData(apiBase + "regex.json");
+                response.EnsureSuccessStatusCode();
+
+                return await response.Content.ReadAsByteArrayAsync()
+                    .ConfigureAwait(false);
             }
         }
 
index 9ff4a31..5d09936 100644 (file)
@@ -662,6 +662,8 @@ namespace OpenTween
             ////設定読み出し
             LoadConfig();
 
+            ThumbnailGenerator.InitializeGenerator();
+
             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance.Value;
             imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
             imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
@@ -670,8 +672,6 @@ namespace OpenTween
                 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
                     this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
 
-            ThumbnailGenerator.InitializeGenerator();
-
             //新着バルーン通知のチェック状態設定
             NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;