Ver Fonte

work on official google translate API

Scrublord1336 há 6 anos atrás
pai
commit
6b3d187543

+ 3 - 1
src/XUnity.AutoTranslator.Plugin.Core/Configuration/Settings.cs

@@ -59,6 +59,7 @@ namespace XUnity.AutoTranslator.Plugin.Core.Configuration
       public static bool EnableBatching;
       public static bool TrimAllText;
       public static bool EnableUIResizing;
+      public static string GoogleAPIKey;
 
       public static bool CopyToClipboard;
       public static int MaxClipboardCopyCharacters;
@@ -106,7 +107,8 @@ namespace XUnity.AutoTranslator.Plugin.Core.Configuration
          EnableUIResizing = Config.Current.Preferences[ "Behaviour" ][ "EnableUIResizing" ].GetOrDefault( true );
          EnableBatching = Config.Current.Preferences[ "Behaviour" ][ "EnableBatching" ].GetOrDefault( true );
          TrimAllText = Config.Current.Preferences[ "Behaviour" ][ "TrimAllText" ].GetOrDefault( Types.AdvEngine == null );
-         
+
+         GoogleAPIKey = Config.Current.Preferences[ "GoogleLegitimate" ][ "GoogleAPIKey" ].GetOrDefault( "" );
 
          BaiduAppId = Config.Current.Preferences[ "Baidu" ][ "BaiduAppId" ].GetOrDefault( "" );
          BaiduAppSecret = Config.Current.Preferences[ "Baidu" ][ "BaiduAppSecret" ].GetOrDefault( "" );

+ 2 - 0
src/XUnity.AutoTranslator.Plugin.Core/Constants/KnownEndpointNames.cs

@@ -11,6 +11,8 @@ namespace XUnity.AutoTranslator.Plugin.Core.Constants
 
       public const string GoogleTranslateHack = "GoogleTranslateHack";
 
+      public const string GoogleTranslateLegitimate = "GoogleTranslateLegitimate";
+
       public const string BaiduTranslate = "BaiduTranslate";
 
       public const string YandexTranslate = "YandexTranslate";

+ 2 - 0
src/XUnity.AutoTranslator.Plugin.Core/KnownEndpoints.cs

@@ -17,6 +17,8 @@ namespace XUnity.AutoTranslator.Plugin.Core
          {
             case KnownEndpointNames.GoogleTranslate:
                return new GoogleTranslateEndpoint();
+            case KnownEndpointNames.GoogleTranslateLegitimate:
+               return new GoogleTranslateLegitimateEndpoint();
             case KnownEndpointNames.GoogleTranslateHack:
                return new GoogleTranslateHackEndpoint();
             case KnownEndpointNames.BaiduTranslate:

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

@@ -0,0 +1,109 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Net;
+using System.Reflection;
+using System.Text;
+using Harmony;
+using Jurassic;
+using SimpleJSON;
+using UnityEngine;
+using XUnity.AutoTranslator.Plugin.Core.Configuration;
+using XUnity.AutoTranslator.Plugin.Core.Constants;
+using XUnity.AutoTranslator.Plugin.Core.Extensions;
+
+namespace XUnity.AutoTranslator.Plugin.Core.Web
+{
+   public class GoogleTranslateLegitimateEndpoint : KnownHttpEndpoint
+   {
+      private static readonly string HttpsServicePointTemplateUrl = "https://translation.googleapis.com/language/translate/v2?key={0}";
+
+      public GoogleTranslateLegitimateEndpoint()
+      {
+         // Configure service points / service point manager
+         ServicePointManager.ServerCertificateValidationCallback += Security.AlwaysAllowByHosts( "translation.googleapis.com" );
+         SetupServicePoints( "https://translation.googleapis.com" );
+      }
+
+      public override bool SupportsLineSplitting => true;
+
+      public override void ApplyHeaders( WebHeaderCollection headers )
+      {
+      }
+
+      public override bool TryExtractTranslated( string result, out string translated )
+      {
+         try
+         {
+            var obj = JsonUtility.FromJson<GResponse>( result );
+            var translations = obj?.data?.translations;
+            if( translations != null && translations.Count > 0 )
+            {
+               translated = translations[ 0 ]?.translatedText;
+               return true;
+            }
+            else
+            {
+               translated = string.Empty;
+               return true;
+            }
+         }
+         catch
+         {
+            translated = null;
+            return false;
+         }
+      }
+
+      public override string GetServiceUrl( string untranslatedText, string from, string to )
+      {
+         return string.Format( HttpsServicePointTemplateUrl, WWW.EscapeURL( Settings.GoogleAPIKey ) );
+      }
+
+      public override string GetRequestObject( string untranslatedText, string from, string to )
+      {
+         return JsonUtility.ToJson( new GRequest
+         {
+            q = untranslatedText,
+            target = to,
+            source = from,
+            format = "text"
+         } );
+      }
+
+      public override bool ShouldGetSecondChanceAfterFailure()
+      {
+         return false;
+      }
+   }
+
+   [Serializable]
+   public class GRequest
+   {
+      public string q { get; set; }
+
+      public string target { get; set; }
+
+      public string source { get; set; }
+
+      public string format { get; set; }
+   }
+
+   public class GResponse
+   {
+      public GData data { get; set; }
+   }
+
+   public class GData
+   {
+      public List<GTranslation> translations { get; set; }
+   }
+
+   public class GTranslation
+   {
+      public string translatedText { get; set; }
+   }
+
+}

+ 16 - 2
src/XUnity.AutoTranslator.Plugin.Core/Web/KnownHttpEndpoint.cs

@@ -32,7 +32,7 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
       protected void SetupServicePoints( params string[] endpoints )
       {
          _servicePoints = new ServicePoint[ endpoints.Length ];
-         
+
          for( int i = 0 ; i < endpoints.Length ; i++ )
          {
             var endpoint = endpoints[ i ];
@@ -60,8 +60,17 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
             {
                var client = GetClient();
                var url = GetServiceUrl( untranslatedText, from, to );
+               var request = GetRequestObject( untranslatedText, from, to );
                ApplyHeaders( client.Headers );
-               result = client.GetDownloadResult( new Uri( url ) );
+
+               if( request != null )
+               {
+                  result = client.GetDownloadResult( new Uri( url ), request );
+               }
+               else
+               {
+                  result = client.GetDownloadResult( new Uri( url ) );
+               }
             }
             catch( Exception e )
             {
@@ -152,6 +161,11 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
 
       public abstract bool TryExtractTranslated( string result, out string translated );
 
+      public virtual string GetRequestObject( string untranslatedText, string from, string to )
+      {
+         return null;
+      }
+
       public virtual void WriteCookies( HttpWebResponse response )
       {
 

+ 71 - 51
src/XUnity.AutoTranslator.Plugin.Core/Web/MyWebClient.cs

@@ -14,6 +14,7 @@ using System.Threading;
 namespace XUnity.AutoTranslator.Plugin.Core.Web
 {
    public delegate void MyDownloadStringCompletedEventHandler( object sender, MyDownloadStringCompletedEventArgs e );
+   public delegate void MyUploadStringCompletedEventHandler( object sender, MyUploadStringCompletedEventArgs e );
 
    public class MyDownloadStringCompletedEventArgs : AsyncCompletedEventArgs
    {
@@ -33,6 +34,24 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
          }
       }
    }
+   public class MyUploadStringCompletedEventArgs : AsyncCompletedEventArgs
+   {
+      private string result;
+
+      internal MyUploadStringCompletedEventArgs( string result, Exception error, bool cancelled, object userState ) : base( error, cancelled, userState )
+      {
+         this.result = result;
+      }
+
+      public string Result
+      {
+         get
+         {
+            base.RaiseExceptionIfNecessary();
+            return this.result;
+         }
+      }
+   }
 
    public class MyAsyncCompletedEventArgs : EventArgs
    {
@@ -102,6 +121,7 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
       private static readonly string urlEncodedCType = "application/x-www-form-urlencoded";
 
       public event MyDownloadStringCompletedEventHandler DownloadStringCompleted;
+      public event MyUploadStringCompletedEventHandler UploadStringCompleted;
 
       static MyWebClient()
       {
@@ -641,14 +661,14 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
       //   }
       //}
 
-      //protected virtual void OnUploadStringCompleted( UploadStringCompletedEventArgs args )
-      //{
-      //   this.CompleteAsync();
-      //   if( this.UploadStringCompleted != null )
-      //   {
-      //      this.UploadStringCompleted( this, args );
-      //   }
-      //}
+      protected virtual void OnUploadStringCompleted( MyUploadStringCompletedEventArgs args )
+      {
+         this.CompleteAsync();
+         if( this.UploadStringCompleted != null )
+         {
+            this.UploadStringCompleted( this, args );
+         }
+      }
 
       //protected virtual void OnUploadValuesCompleted( UploadValuesCompletedEventArgs args )
       //{
@@ -1291,51 +1311,51 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
          return this.encoding.GetString( bytes );
       }
 
-      //public void UploadStringAsync( Uri address, string data )
-      //{
-      //   this.UploadStringAsync( address, null, data );
-      //}
+      public void UploadStringAsync( Uri address, string data )
+      {
+         this.UploadStringAsync( address, null, data );
+      }
 
-      //public void UploadStringAsync( Uri address, string method, string data )
-      //{
-      //   this.UploadStringAsync( address, method, data, null );
-      //}
+      public void UploadStringAsync( Uri address, string method, string data )
+      {
+         this.UploadStringAsync( address, method, data, null );
+      }
 
-      //public void UploadStringAsync( Uri address, string method, string data, object userToken )
-      //{
-      //   if( address == null )
-      //   {
-      //      throw new ArgumentNullException( "address" );
-      //   }
-      //   if( data == null )
-      //   {
-      //      throw new ArgumentNullException( "data" );
-      //   }
-      //   MyWebClient client = this;
-      //   lock( client )
-      //   {
-      //      this.CheckBusy();
-      //      this.async = true;
-      //      object[] parameter = new object[] { address, method, data, userToken };
-      //      ThreadPool.QueueUserWorkItem( delegate ( object state )
-      //      {
-      //         object[] objArray = (object[])state;
-      //         try
-      //         {
-      //            string result = this.UploadString( (Uri)objArray[ 0 ], (string)objArray[ 1 ], (string)objArray[ 2 ] );
-      //            this.OnUploadStringCompleted( new UploadStringCompletedEventArgs( result, null, false, objArray[ 3 ] ) );
-      //         }
-      //         catch( ThreadInterruptedException )
-      //         {
-      //            this.OnUploadStringCompleted( new UploadStringCompletedEventArgs( null, null, true, objArray[ 3 ] ) );
-      //         }
-      //         catch( Exception exception )
-      //         {
-      //            this.OnUploadStringCompleted( new UploadStringCompletedEventArgs( null, exception, false, objArray[ 3 ] ) );
-      //         }
-      //      }, parameter );
-      //   }
-      //}
+      public void UploadStringAsync( Uri address, string method, string data, object userToken )
+      {
+         if( address == null )
+         {
+            throw new ArgumentNullException( "address" );
+         }
+         if( data == null )
+         {
+            throw new ArgumentNullException( "data" );
+         }
+         MyWebClient client = this;
+         lock( client )
+         {
+            this.CheckBusy();
+            this.async = true;
+            object[] parameter = new object[] { address, method, data, userToken };
+            ThreadPool.QueueUserWorkItem( delegate ( object state )
+            {
+               object[] objArray = (object[])state;
+               try
+               {
+                  string result = this.UploadString( (Uri)objArray[ 0 ], (string)objArray[ 1 ], (string)objArray[ 2 ] );
+                  this.OnUploadStringCompleted( new MyUploadStringCompletedEventArgs( result, null, false, objArray[ 3 ] ) );
+               }
+               catch( ThreadInterruptedException )
+               {
+                  this.OnUploadStringCompleted( new MyUploadStringCompletedEventArgs( null, null, true, objArray[ 3 ] ) );
+               }
+               catch( Exception exception )
+               {
+                  this.OnUploadStringCompleted( new MyUploadStringCompletedEventArgs( null, exception, false, objArray[ 3 ] ) );
+               }
+            }, parameter );
+         }
+      }
 
       public byte[] UploadValues( string address, NameValueCollection data )
       {

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

@@ -21,6 +21,34 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
          _httpEndpoint = endpoint;
          Encoding = Encoding.UTF8;
          DownloadStringCompleted += UnityWebClient_DownloadStringCompleted;
+         UploadStringCompleted += UnityWebClient_UploadStringCompleted;
+      }
+
+      private void UnityWebClient_UploadStringCompleted( object sender, MyUploadStringCompletedEventArgs 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 );
       }
 
       private void UnityWebClient_DownloadStringCompleted( object sender, MyDownloadStringCompletedEventArgs ev )
@@ -91,6 +119,13 @@ namespace XUnity.AutoTranslator.Plugin.Core.Web
          DownloadStringAsync( address, handle );
          return handle;
       }
+
+      public DownloadResult GetDownloadResult( Uri address, string request )
+      {
+         var handle = new DownloadResult();
+         UploadStringAsync( address, "POST", request, handle );
+         return handle;
+      }
    }
 
    public class DownloadResult : CustomYieldInstruction