Jelajahi Sumber

work on UnityWebClient as WWW replacement

Scrublord1336 6 tahun lalu
induk
melakukan
1dddbb5c14

+ 15 - 42
src/XUnity.AutoTranslator.Plugin.Core/Web/AutoTranslateClient.cs

@@ -59,16 +59,13 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
             _endpoint.EndSetup( yieldable );
          }
 
-
          var url = _endpoint.GetServiceUrl( untranslated, from, to );
-         var headers = new Dictionary<string, string>();
-         _endpoint.ApplyHeaders( headers );
-
-         object www = WwwConstructor.Invoke( new object[] { url, null, headers } );
+         _endpoint.ApplyHeaders( UnityWebClient.Default.Headers );
+         var result = UnityWebClient.Default.GetDownloadResult( new Uri( url ) );
          try
          {
             _runningTranslations++;
-            yield return www;
+            yield return result;
             _runningTranslations--;
 
             _translationCount++;
@@ -92,56 +89,32 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
                }
             }
 
-
-            string error = null;
-            try
-            {
-               error = (string)AccessTools.Property( Types.WWW, "error" ).GetValue( www, null );
-            }
-            catch( Exception e )
+            if( _translationCount % 100 == 0 )
             {
-               error = e.ToString();
+               UnityWebClient.Default.ClearCookies();
             }
 
-            if( error != null )
-            {
-               failure();
-            }
-            else
+
+            if( result.Succeeded )
             {
-               var text = (string)AccessTools.Property( Types.WWW, "text" ).GetValue( www, null ); ;
-               if( text != null )
+               if( _endpoint.TryExtractTranslated( result.Result, out var translatedText ) )
                {
-                  try
-                  {
-                     if( _endpoint.TryExtractTranslated( text, out var translatedText ) )
-                     {
-                        translatedText = translatedText ?? string.Empty;
-                        success( translatedText );
-                     }
-                     else
-                     {
-                        failure();
-                     }
-                  }
-                  catch
-                  {
-                     failure();
-                  }
+                  translatedText = translatedText ?? string.Empty;
+                  success( translatedText );
                }
                else
                {
                   failure();
                }
             }
+            else
+            {
+               failure();
+            }
          }
          finally
          {
-            var disposable = www as IDisposable;
-            if( disposable != null )
-            {
-               disposable.Dispose();
-            }
+
          }
       }
    }

+ 14 - 22
src/XUnity.AutoTranslator.Plugin.Core/Web/GoogleTranslateEndpoint.cs

@@ -19,7 +19,7 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
    {
       private static readonly ConstructorInfo WwwConstructor = Constants.Types.WWW.GetConstructor( new[] { typeof( string ), typeof( byte[] ), typeof( Dictionary<string, string> ) } );
 
-      //private static readonly string CertificateIssuer = "CN=Google Internet Authority G3, O=Google Trust Services, C=US";
+      private static readonly string CertificateIssuer = "CN=Google Internet Authority G3, O=Google Trust Services, C=US";
       private static ServicePoint ServicePoint;
       private static readonly string HttpServicePointTemplateUrl = "http://translate.googleapis.com/translate_a/single?client=t&dt=t&sl={0}&tl={1}&ie=UTF-8&oe=UTF-8&tk={2}&q={3}";
       private static readonly string HttpsServicePointTemplateUrl = "https://translate.googleapis.com/translate_a/single?client=t&dt=t&sl={0}&tl={1}&ie=UTF-8&oe=UTF-8&tk={2}&q={3}";
@@ -50,7 +50,6 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
       {
          headers[ HttpRequestHeader.UserAgent ] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36";
          headers[ HttpRequestHeader.Accept ] = "*/*";
-         headers[ HttpRequestHeader.AcceptCharset ] = "UTF-8";
       }
 
       public override bool IsSettingUp()
@@ -66,11 +65,9 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
 
             try
             {
-               var headers = new Dictionary<string, string>();
-               ApplyHeaders( headers );
-               object www = WwwConstructor.Invoke( new object[] { Settings.EnableSSL ? HttpsTranslateUserSite : HttpTranslateUserSite, null, headers } );
-
-               return www;
+               ApplyHeaders( UnityWebClient.Default.Headers );
+               var result = UnityWebClient.Default.GetDownloadResult( new Uri( Settings.EnableSSL ? HttpsTranslateUserSite : HttpTranslateUserSite ) );
+               return result;
             }
             catch( Exception e )
             {
@@ -87,21 +84,16 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
 
       public override void EndSetup( object www )
       {
-         string error = null;
-         try
-         {
-            error = (string)AccessTools.Property( Constants.Types.WWW, "error" ).GetValue( www, null );
-         }
-         catch( Exception e )
-         {
-            error = e.ToString();
-         }
+         Console.WriteLine( "EndSetup: " + www );
 
-         if( error == null )
+         var dresult = www as DownloadResult;
+         var error = dresult.Error;
+
+         if( dresult.Succeeded )
          {
             try
             {
-               var html = (string)AccessTools.Property( Constants.Types.WWW, "text" ).GetValue( www, null );
+               var html = dresult.Result;
 
                const string lookup = "TKK=eval('";
                var lookupIndex = html.IndexOf( lookup ) + lookup.Length;
@@ -205,10 +197,10 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
       {
          try
          {
-            //ServicePointManager.ServerCertificateValidationCallback += ( sender, certificate, chain, sslPolicyErrors ) =>
-            //{
-            //   return certificate.Issuer == CertificateIssuer;
-            //};
+            ServicePointManager.ServerCertificateValidationCallback += ( sender, certificate, chain, sslPolicyErrors ) =>
+            {
+               return certificate.Issuer == CertificateIssuer;
+            };
 
             ServicePoint = ServicePointManager.FindServicePoint( new Uri( "http://translate.googleapis.com" ) );
             ServicePoint.ConnectionLimit = GetMaxConcurrency();

+ 109 - 0
src/XUnity.AutoTranslator.Plugin.Core/Web/UnityWebClient.cs

@@ -0,0 +1,109 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Text;
+using UnityEngine;
+
+namespace XUnity.AutoTranslator.Plugin.Core.Web
+{
+   public class UnityWebClient : WebClient
+   {
+      private static UnityWebClient _default;
+
+      public static UnityWebClient Default
+      {
+         get
+         {
+            if( _default == null )
+            {
+               _default = new UnityWebClient();
+            }
+            return _default;
+         }
+      }
+
+      private CookieContainer _container = new CookieContainer();
+
+      public UnityWebClient()
+      {
+         Encoding = Encoding.UTF8;
+         DownloadStringCompleted += UnityWebClient_DownloadStringCompleted;
+      }
+
+      public void ClearCookies()
+      {
+         _container = new CookieContainer();
+      }
+
+      private void UnityWebClient_DownloadStringCompleted( object sender, DownloadStringCompletedEventArgs ev )
+      {
+         var handle = ev.UserState as DownloadResult;
+
+         // obtain result, error, etc.
+         string text = null;
+         string error = null;
+
+         try
+         {
+            if( ev.Error == null )
+            {
+               text = ev.Result ?? string.Empty;
+            }
+            else
+            {
+               error = ev.Error.ToString();
+            }
+         }
+         catch( Exception e )
+         {
+            error = e.ToString();
+         }
+
+         handle.SetCompleted( text, error );
+      }
+
+      protected override WebRequest GetWebRequest( Uri address )
+      {
+         var request = base.GetWebRequest( address );
+         var httpRequest = request as HttpWebRequest;
+         if( httpRequest != null )
+         {
+            httpRequest.CookieContainer = _container;
+         }
+         return request;
+      }
+
+      public DownloadResult GetDownloadResult( Uri address )
+      {
+         var handle = new DownloadResult();
+
+         DownloadStringAsync( address, handle );
+
+         Console.WriteLine( "GetDownloadResult: " + address );
+
+         return handle;
+      }
+   }
+
+   public class DownloadResult : CustomYieldInstruction
+   {
+      private bool _isCompleted = false;
+
+      public void SetCompleted( string result, string error )
+      {
+         _isCompleted = true;
+         Result = result;
+         Error = error;
+      }
+
+      public override bool keepWaiting => !_isCompleted;
+
+      public string Result { get; set; }
+
+      public string Error { get; set; }
+
+      public bool Succeeded => Error == null;
+   }
+}