[gnome-subtitles/gtk3] Disabling GoogleTranslate functionality



commit 973d81d258e2bbd8c6344fd1820e6660c4d534ac
Author: Pedro Castro <pedro gnomesubtitles org>
Date:   Sun May 6 11:10:44 2018 +0100

    Disabling GoogleTranslate functionality
    
    GT is no longer free.

 src/Glade/MainWindow.ui                            |   47 +---
 .../Core/Command/TranslatorCommand.cs              |  190 +++++++-------
 src/GnomeSubtitles/Core/EventHandlers.cs           |   12 +-
 src/GnomeSubtitles/Ui/Menus.cs                     |   10 +-
 src/GnomeSubtitles/Ui/WidgetNames.cs               |    4 +-
 src/SubLib/Core/Translator.cs                      |  268 ++++++++++----------
 6 files changed, 255 insertions(+), 276 deletions(-)
---
diff --git a/src/Glade/MainWindow.ui b/src/Glade/MainWindow.ui
index 397aeec..0f4f1ed 100644
--- a/src/Glade/MainWindow.ui
+++ b/src/Glade/MainWindow.ui
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<!-- Generated with glade 3.20.0 -->
+<!-- Generated with glade 3.22.1 -->
 <interface>
   <requires lib="gtk+" version="3.12"/>
   <object class="GtkAdjustment" id="durationSpinButtonAdjustment">
@@ -29,6 +29,9 @@
     <signal name="delete-event" handler="OnWindowDelete" swapped="no"/>
     <signal name="size-allocate" handler="OnSizeAllocated" swapped="no"/>
     <child>
+      <placeholder/>
+    </child>
+    <child>
       <object class="GtkBox" id="box1">
         <property name="visible">True</property>
         <property name="can_focus">False</property>
@@ -248,8 +251,8 @@
                         <property name="label" translatable="yes">_Redo</property>
                         <property name="use_underline">True</property>
                         <signal name="activate" handler="OnEditRedo" swapped="no"/>
-                        <accelerator key="z" signal="activate" modifiers="GDK_SHIFT_MASK | 
GDK_CONTROL_MASK"/>
                         <accelerator key="y" signal="activate" modifiers="GDK_CONTROL_MASK"/>
+                        <accelerator key="z" signal="activate" modifiers="GDK_SHIFT_MASK | 
GDK_CONTROL_MASK"/>
                       </object>
                     </child>
                     <child>
@@ -571,8 +574,8 @@
                         <property name="label" translatable="yes">Find Ne_xt</property>
                         <property name="use_underline">True</property>
                         <signal name="activate" handler="OnSearchFindNext" swapped="no"/>
-                        <accelerator key="g" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                         <accelerator key="F3" signal="activate"/>
+                        <accelerator key="g" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                       </object>
                     </child>
                     <child>
@@ -582,8 +585,8 @@
                         <property name="label" translatable="yes">Find Pre_vious</property>
                         <property name="use_underline">True</property>
                         <signal name="activate" handler="OnSearchFindPrevious" swapped="no"/>
-                        <accelerator key="g" signal="activate" modifiers="GDK_SHIFT_MASK | 
GDK_CONTROL_MASK"/>
                         <accelerator key="F3" signal="activate" modifiers="GDK_SHIFT_MASK"/>
+                        <accelerator key="g" signal="activate" modifiers="GDK_SHIFT_MASK | 
GDK_CONTROL_MASK"/>
                       </object>
                     </child>
                     <child>
@@ -824,8 +827,8 @@
                         <property name="label" translatable="yes">_Play / Pause</property>
                         <property name="use_underline">True</property>
                         <signal name="activate" handler="OnVideoPlayPause" swapped="no"/>
-                        <accelerator key="p" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                         <accelerator key="F5" signal="activate"/>
+                        <accelerator key="p" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                       </object>
                     </child>
                     <child>
@@ -847,8 +850,8 @@
                         <property name="label" translatable="yes">R_ewind</property>
                         <property name="use_underline">True</property>
                         <signal name="activate" handler="OnVideoRewind" swapped="no"/>
-                        <accelerator key="k" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                         <accelerator key="F6" signal="activate"/>
+                        <accelerator key="k" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                       </object>
                     </child>
                     <child>
@@ -859,8 +862,8 @@
                         <property name="label" translatable="yes">_Forward</property>
                         <property name="use_underline">True</property>
                         <signal name="activate" handler="OnVideoForward" swapped="no"/>
-                        <accelerator key="l" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                         <accelerator key="F7" signal="activate"/>
+                        <accelerator key="l" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                       </object>
                     </child>
                     <child>
@@ -888,8 +891,8 @@
                         <property name="label" translatable="yes">Seek _to Selection</property>
                         <property name="use_underline">True</property>
                         <signal name="activate" handler="OnVideoSeekToSelection" swapped="no"/>
-                        <accelerator key="r" signal="activate" modifiers="GDK_SHIFT_MASK | 
GDK_CONTROL_MASK"/>
                         <accelerator key="F4" signal="activate" modifiers="GDK_SHIFT_MASK | 
GDK_CONTROL_MASK"/>
+                        <accelerator key="r" signal="activate" modifiers="GDK_SHIFT_MASK | 
GDK_CONTROL_MASK"/>
                       </object>
                     </child>
                     <child>
@@ -900,8 +903,8 @@
                         <property name="label" translatable="yes">Select _Nearest Subtitle</property>
                         <property name="use_underline">True</property>
                         <signal name="activate" handler="OnVideoSelectNearestSubtitle" swapped="no"/>
-                        <accelerator key="r" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                         <accelerator key="F4" signal="activate" modifiers="GDK_CONTROL_MASK"/>
+                        <accelerator key="r" signal="activate" modifiers="GDK_CONTROL_MASK"/>
                       </object>
                     </child>
                     <child>
@@ -978,32 +981,6 @@
                         <signal name="activate" handler="OnToolsSetLanguages" swapped="no"/>
                       </object>
                     </child>
-                    <child>
-                      <object class="GtkSeparatorMenuItem" id="toolsSeparator1">
-                        <property name="visible">True</property>
-                        <property name="can_focus">False</property>
-                      </object>
-                    </child>
-                    <child>
-                      <object class="GtkMenuItem" id="toolsTranslateText">
-                        <property name="visible">True</property>
-                        <property name="sensitive">False</property>
-                        <property name="can_focus">False</property>
-                        <property name="label" translatable="yes">Translate _Text → Translation</property>
-                        <property name="use_underline">True</property>
-                        <signal name="activate" handler="OnToolsTranslateText" swapped="no"/>
-                      </object>
-                    </child>
-                    <child>
-                      <object class="GtkMenuItem" id="toolsTranslateTranslation">
-                        <property name="visible">True</property>
-                        <property name="sensitive">False</property>
-                        <property name="can_focus">False</property>
-                        <property name="label" translatable="yes">Translate Translatio_n → Text</property>
-                        <property name="use_underline">True</property>
-                        <signal name="activate" handler="OnToolsTranslateTranslation" swapped="no"/>
-                      </object>
-                    </child>
                   </object>
                 </child>
               </object>
diff --git a/src/GnomeSubtitles/Core/Command/TranslatorCommand.cs 
b/src/GnomeSubtitles/Core/Command/TranslatorCommand.cs
index 6095288..78ee1be 100644
--- a/src/GnomeSubtitles/Core/Command/TranslatorCommand.cs
+++ b/src/GnomeSubtitles/Core/Command/TranslatorCommand.cs
@@ -1,107 +1,107 @@
-/*
- * This file is part of Gnome Subtitles.
- * Copyright (C) 2011-2017 Pedro Castro
- *
- * Gnome Subtitles is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Gnome Subtitles is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
- */
+///*
+// * This file is part of Gnome Subtitles.
+// * Copyright (C) 2011-2017 Pedro Castro
+// *
+// * Gnome Subtitles is free software; you can redistribute it and/or modify
+// * it under the terms of the GNU General Public License as published by
+// * the Free Software Foundation; either version 2 of the License, or
+// * (at your option) any later version.
+// *
+// * Gnome Subtitles is distributed in the hope that it will be useful,
+// * but WITHOUT ANY WARRANTY; without even the implied warranty of
+// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// * GNU General Public License for more details.
+// *
+// * You should have received a copy of the GNU General Public License
+// * along with this program; if not, write to the Free Software
+// * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+// */
 
-using GnomeSubtitles.Dialog;
-using GnomeSubtitles.Dialog.Unmanaged;
-using GnomeSubtitles.Ui.Edit;
-using Gtk;
-using Mono.Unix;
-using SubLib;
-using SubLib.Core;
-using SubLib.Core.Domain;
-using SubLib.Exceptions;
-using SubLib.Util;
-using System;
+//using GnomeSubtitles.Dialog;
+//using GnomeSubtitles.Dialog.Unmanaged;
+//using GnomeSubtitles.Ui.Edit;
+//using Gtk;
+//using Mono.Unix;
+//using SubLib;
+//using SubLib.Core;
+//using SubLib.Core.Domain;
+//using SubLib.Exceptions;
+//using SubLib.Util;
+//using System;
 
-namespace GnomeSubtitles.Core.Command {
+//namespace GnomeSubtitles.Core.Command {
 
-public class TranslatorCommand : FixedSingleSelectionCommand {
-       private string previousValue = null; // initially, it's the former text replaced by translation
-       private bool leftToRight = true; // direction of translation
-       private static string description = Catalog.GetString("Translating");
+//public class TranslatorCommand : FixedSingleSelectionCommand {
+//     private string previousValue = null; // initially, it's the former text replaced by translation
+//     private bool leftToRight = true; // direction of translation
+//     private static string description = Catalog.GetString("Translating");
 
-       public TranslatorCommand (bool leftToRight) : base(description, false, true) {
-               this.leftToRight = leftToRight;
-       }
+//     public TranslatorCommand (bool leftToRight) : base(description, false, true) {
+//             this.leftToRight = leftToRight;
+//     }
 
-       /* Public members */
+//     /* Public members */
 
-       protected override bool ChangeValues () {
-               /* If previousText is null, it's the first time the command is executed, so do translation.
-                  Otherwise, it's undo or redo, so we only need to swap the values */
-               if (previousValue == null)
-                       return DoTranslation();
-               else {
-                       Subtitle subtitle = Base.Document.Subtitles[Path];
-                       if (leftToRight) {
-                               string currentValue = subtitle.Translation.Get();
-                               subtitle.Translation.Set(this.previousValue);
-                               this.previousValue = currentValue;
-                       }
-                       else {
-                               string currentValue = subtitle.Text.Get();
-                               subtitle.Text.Set(this.previousValue);
-                               this.previousValue = currentValue;
-                       }
-                       return true;
-               }
-       }
+//     protected override bool ChangeValues () {
+//             /* If previousText is null, it's the first time the command is executed, so do translation.
+//                Otherwise, it's undo or redo, so we only need to swap the values */
+//             if (previousValue == null)
+//                     return DoTranslation();
+//             else {
+//                     Subtitle subtitle = Base.Document.Subtitles[Path];
+//                     if (leftToRight) {
+//                             string currentValue = subtitle.Translation.Get();
+//                             subtitle.Translation.Set(this.previousValue);
+//                             this.previousValue = currentValue;
+//                     }
+//                     else {
+//                             string currentValue = subtitle.Text.Get();
+//                             subtitle.Text.Set(this.previousValue);
+//                             this.previousValue = currentValue;
+//                     }
+//                     return true;
+//             }
+//     }
 
-       private bool DoTranslation () {
-               if (Base.Ui.View.Selection.Count != 1) { //TODO: for now, only works if 1 subtitle is selected
-                       return false;
-               }
+//     private bool DoTranslation () {
+//             if (Base.Ui.View.Selection.Count != 1) { //TODO: for now, only works if 1 subtitle is selected
+//                     return false;
+//             }
 
-               /* Show language selection dialog if one of the languages isn't selected */
-               if (!Base.SpellLanguages.HasActiveTextLanguage || 
!Base.SpellLanguages.HasActiveTranslationLanguage) {
-                       SetLanguagesDialog dialog = Base.Dialogs.Get(typeof(SetLanguagesDialog)) as 
SetLanguagesDialog;
-                       dialog.Show();
-                       dialog.WaitForResponse();
-                       if (!Base.SpellLanguages.HasActiveTextLanguage || 
!Base.SpellLanguages.HasActiveTranslationLanguage) {
-                               return false; //Both must be selected, if they aren't we just don't do 
anything here
-                       }
-               }
+//             /* Show language selection dialog if one of the languages isn't selected */
+//             if (!Base.SpellLanguages.HasActiveTextLanguage || 
!Base.SpellLanguages.HasActiveTranslationLanguage) {
+//                     SetLanguagesDialog dialog = Base.Dialogs.Get(typeof(SetLanguagesDialog)) as 
SetLanguagesDialog;
+//                     dialog.Show();
+//                     dialog.WaitForResponse();
+//                     if (!Base.SpellLanguages.HasActiveTextLanguage || 
!Base.SpellLanguages.HasActiveTranslationLanguage) {
+//                             return false; //Both must be selected, if they aren't we just don't do 
anything here
+//                     }
+//             }
 
-               try {
-                       Subtitle subtitle = Base.Document.Subtitles[Path];
-                       if (leftToRight) {
-                               this.previousValue = subtitle.Translation.Get();
-                               string translatedText = Translator.TranslateText(subtitle.Text.Get(), 
Base.SpellLanguages.ActiveTextLanguage.ID, Base.SpellLanguages.ActiveTranslationLanguage.ID, 
Translator.TIMEOUT);
-                               subtitle.Translation.Set(translatedText);
-                       }
-                       else {
-                               this.previousValue = subtitle.Text.Get();
-                               string translatedText = Translator.TranslateText(subtitle.Translation.Get(), 
Base.SpellLanguages.ActiveTranslationLanguage.ID, Base.SpellLanguages.ActiveTextLanguage.ID, 
Translator.TIMEOUT);
-                               subtitle.Text.Set(translatedText);
-                       }
+//             try {
+//                     Subtitle subtitle = Base.Document.Subtitles[Path];
+//                     if (leftToRight) {
+//                             this.previousValue = subtitle.Translation.Get();
+//                             string translatedText = Translator.TranslateText(subtitle.Text.Get(), 
Base.SpellLanguages.ActiveTextLanguage.ID, Base.SpellLanguages.ActiveTranslationLanguage.ID, 
Translator.TIMEOUT);
+//                             subtitle.Translation.Set(translatedText);
+//                     }
+//                     else {
+//                             this.previousValue = subtitle.Text.Get();
+//                             string translatedText = Translator.TranslateText(subtitle.Translation.Get(), 
Base.SpellLanguages.ActiveTranslationLanguage.ID, Base.SpellLanguages.ActiveTextLanguage.ID, 
Translator.TIMEOUT);
+//                             subtitle.Text.Set(translatedText);
+//                     }
 
-                       //TODO: if only one subtitle is selected, set the cursor on the translated text box 
and select its text. If multiple subtitles translated, select those subtitles.
-                       return true;
-               }
-               catch (TranslatorException e) { //TODO know which exceptions are originally thrown. Check if 
it's possible to have the second error message in the application language.
-                       Logger.Error(e);
-                       BasicErrorDialog errorDialog = new BasicErrorDialog(Catalog.GetString("Could not 
translate the chosen subtitle."), e.Message);
-                       errorDialog.Show();
-                       return false;
-               }
-       }
+//                     //TODO: if only one subtitle is selected, set the cursor on the translated text box 
and select its text. If multiple subtitles translated, select those subtitles.
+//                     return true;
+//             }
+//             catch (TranslatorException e) { //TODO know which exceptions are originally thrown. Check if 
it's possible to have the second error message in the application language.
+//                     Logger.Error(e);
+//                     BasicErrorDialog errorDialog = new BasicErrorDialog(Catalog.GetString("Could not 
translate the chosen subtitle."), e.Message);
+//                     errorDialog.Show();
+//                     return false;
+//             }
+//     }
 
-}
+//}
 
-}
+//}
diff --git a/src/GnomeSubtitles/Core/EventHandlers.cs b/src/GnomeSubtitles/Core/EventHandlers.cs
index 4ce31c8..14897f6 100644
--- a/src/GnomeSubtitles/Core/EventHandlers.cs
+++ b/src/GnomeSubtitles/Core/EventHandlers.cs
@@ -384,13 +384,13 @@ public class EventHandlers {
                Base.Dialogs.Get(typeof(SetLanguagesDialog)).Show();
        }
 
-       public void OnToolsTranslateText (object o, EventArgs args) {
-               Base.CommandManager.Execute(new TranslatorCommand(true));
-       }
+       //public void OnToolsTranslateText (object o, EventArgs args) {
+       //      Base.CommandManager.Execute(new TranslatorCommand(true));
+       //}
 
-       public void OnToolsTranslateTranslation (object o, EventArgs args) {
-               Base.CommandManager.Execute(new TranslatorCommand(false));
-       }
+       //public void OnToolsTranslateTranslation (object o, EventArgs args) {
+       //      Base.CommandManager.Execute(new TranslatorCommand(false));
+       //}
 
 
        /*      Help Menu */
diff --git a/src/GnomeSubtitles/Ui/Menus.cs b/src/GnomeSubtitles/Ui/Menus.cs
index 9608fd7..66b7cf0 100644
--- a/src/GnomeSubtitles/Ui/Menus.cs
+++ b/src/GnomeSubtitles/Ui/Menus.cs
@@ -140,8 +140,8 @@ public class Menus {
        /// <param name="sensitivity">Whether the items are set sensitive.</param>
        private void SetOneSelectionDependentSensitivity (bool sensitivity) {
                SetVideoSelectionDependentSensitivity(sensitivity);
-               SetSensitivity(WidgetNames.ToolsTranslateText, sensitivity && 
Base.Document.IsTranslationLoaded);
-               SetSensitivity(WidgetNames.ToolsTranslateTranslation, sensitivity && 
Base.Document.IsTranslationLoaded);
+//             SetSensitivity(WidgetNames.ToolsTranslateText, sensitivity && 
Base.Document.IsTranslationLoaded);
+//             SetSensitivity(WidgetNames.ToolsTranslateTranslation, sensitivity && 
Base.Document.IsTranslationLoaded);
        }
 
        private void SetSubtitleCountDependentSensitivity (int count) {
@@ -235,9 +235,9 @@ public class Menus {
                SetSensitivity(WidgetNames.FileTranslationClose, sensitivity);
                SetSensitivity(WidgetNames.FileTranslationReload, sensitivity);
 
-               bool oneSubtitleSelected = (Core.Base.Ui.View.Selection.Count == 1);
-               SetSensitivity(WidgetNames.ToolsTranslateText, sensitivity && oneSubtitleSelected);
-               SetSensitivity(WidgetNames.ToolsTranslateTranslation, sensitivity && oneSubtitleSelected);
+//             bool oneSubtitleSelected = (Core.Base.Ui.View.Selection.Count == 1);
+//             SetSensitivity(WidgetNames.ToolsTranslateText, sensitivity && oneSubtitleSelected);
+//             SetSensitivity(WidgetNames.ToolsTranslateTranslation, sensitivity && oneSubtitleSelected);
                SetViewVideoSubtitlesSensitivity();
        }
 
diff --git a/src/GnomeSubtitles/Ui/WidgetNames.cs b/src/GnomeSubtitles/Ui/WidgetNames.cs
index c3dd1dc..81bdf2e 100644
--- a/src/GnomeSubtitles/Ui/WidgetNames.cs
+++ b/src/GnomeSubtitles/Ui/WidgetNames.cs
@@ -92,8 +92,8 @@ public class WidgetNames {
        /* Tools Menu */
        public const string ToolsAutocheckSpelling = "toolsAutocheckSpelling";
        public const string ToolsSetLanguages = "toolsSetLanguages";
-       public const string ToolsTranslateText = "toolsTranslateText";
-       public const string ToolsTranslateTranslation = "toolsTranslateTranslation";
+       //public const string ToolsTranslateText = "toolsTranslateText";
+       //public const string ToolsTranslateTranslation = "toolsTranslateTranslation";
 
 
        /* Toolbar */
diff --git a/src/SubLib/Core/Translator.cs b/src/SubLib/Core/Translator.cs
index 9eedadc..7fea87d 100644
--- a/src/SubLib/Core/Translator.cs
+++ b/src/SubLib/Core/Translator.cs
@@ -1,133 +1,135 @@
-/*
- * This file is part of SubLib.
- * Copyright (C) 2011 Pedro Castro
- *
- * SubLib is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * SubLib is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
- */
-
-using SubLib.Core.Domain;
-using SubLib.Exceptions;
-using System;
-using System.Net;
-using System.IO;
-using System.Globalization;
-using System.Text.RegularExpressions;
-using System.Text;
-
-namespace SubLib.Core {
-       /// <summary>Allows translating subtitles from one language to another using Google Translate 
service.</summary>
-       public class Translator {
-               private const string REQUEST_URL_FORMAT = 
"http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&{0}langpair={1}|{2}";
-               private const string REQUEST_LINE_FORMAT = "q={0}&";
-
-               private const char SPLIT_CHAR = '\n';
-               private const char CULTURE_REPLACEE = '_';
-               private const char CULTURE_REPLACER = '-';
-
-               private const string JSON_RESPONSE_SUCCESS = "200";
-
-               private const string REGEX_ERROR_MATCH = @"^.*\""responseDetails\"": 
(.+),.*\""responseStatus\"":.*([0-9][0-9][0-9]).*$";
-               private const string REGEX_RESPONSE_MATCH = @"\""translatedText\"":\""([^\""]*)";
-               private const int REGEX_MATCH_INDEX_ONE_VALUE = 1;
-               private const int REGEX_MATCH_INDEX_TWO_VALUE = 2;
-
-               public const int TIMEOUT = 3000;
-
-
-               /* Public methods */
-
-               /// <summary>Translates given text between two given languages.</summary>
-               public static string TranslateText (string inputText, string fromLanguage, string toLanguage, 
int timeoutMillis) {
-                       // testing emptiness of the string
-                       if (inputText.Trim().Length == 0)
-                               return String.Empty;
-
-                       // splitting input text into single lines; line-breaks cannot be transferred to 
Google Translate
-                       StringBuilder stringBuilder = new StringBuilder();
-                       foreach (String split in inputText.Split(SPLIT_CHAR)) {
-                               stringBuilder.Append(String.Format(REQUEST_LINE_FORMAT, 
System.Web.HttpUtility.UrlEncode(split)));
-                       }
-
-                       try {
-                   //TODO 'key' parameter could be added
-                               // building request URL
-                               string requestUrl = String.Format(REQUEST_URL_FORMAT, 
stringBuilder.ToString(),
-                       CultureInfo.CreateSpecificCulture(fromLanguage.Replace(CULTURE_REPLACEE, 
CULTURE_REPLACER)).TwoLetterISOLanguageName.ToLowerInvariant(),
-                                   CultureInfo.CreateSpecificCulture(toLanguage.Replace(CULTURE_REPLACEE, 
CULTURE_REPLACER)).TwoLetterISOLanguageName.ToLowerInvariant()
-                   );
-
-                               // translating
-                   HttpWebRequest req = HttpWebRequest.Create(requestUrl) as HttpWebRequest;
-                               req.Timeout = timeoutMillis;
-                               req.Method = WebRequestMethods.Http.Get;
-                HttpWebResponse res = req.GetResponse() as HttpWebResponse;
-
-                               // processing response
-                string responseJson = new StreamReader(res.GetResponseStream()).ReadToEnd();
-
-                return ProcessJson(responseJson);
-            }
-                       catch (Exception e) {
-                               throw new TranslatorException(e.Message);
-            }
-        }
-
-
-               /* Private methods */
-
-               /// <summary>Processes JSON response from Google Translate service.</summary>
-               private static string ProcessJson (string responseJson) {
-                       // fixing english-related quote problem
-                       responseJson = responseJson.Replace("\\\"", "\\u0026quot;");
-
-                       // matching responseStatus
-                       StringBuilder stringBuilder = new StringBuilder();
-                       Match match = Regex.Match(responseJson, REGEX_ERROR_MATCH, RegexOptions.IgnoreCase | 
RegexOptions.Compiled);
-                       if (match.Success && match.Groups.Count > REGEX_MATCH_INDEX_TWO_VALUE && 
match.Groups[REGEX_MATCH_INDEX_TWO_VALUE].Value == JSON_RESPONSE_SUCCESS) {
-
-                               // matching multi-line translated text and building output
-                               bool first = true;
-                   MatchCollection matchCollection = Regex.Matches(responseJson, REGEX_RESPONSE_MATCH, 
RegexOptions.IgnoreCase | RegexOptions.Compiled);
-                               foreach (Match textMatch in matchCollection) {
-                                       if (textMatch.Success && textMatch.Groups.Count > 
REGEX_MATCH_INDEX_ONE_VALUE) {
-                                               if (!first)
-                                                       stringBuilder.Append(SPLIT_CHAR);
-
-                                               
stringBuilder.Append(textMatch.Groups[REGEX_MATCH_INDEX_ONE_VALUE].Value);
-                                               first = false;
-                                       }
-                               }
-
-                               // replacing escaped characters that are not decoded automatically
-                               stringBuilder = stringBuilder.Replace("\\u0026#39", "'");
-                               stringBuilder = stringBuilder.Replace("\\u0026quot;", "\"");
-                               stringBuilder = stringBuilder.Replace("\\u0026amp;", "&");
-                               stringBuilder = stringBuilder.Replace("\\u0026lt;", "<");
-                               stringBuilder = stringBuilder.Replace("\\u0026qt;", ">");
-                               stringBuilder = stringBuilder.Replace("\\u0026amp;", "&");
-                               stringBuilder = stringBuilder.Replace("\\u0026", "&");
-                               stringBuilder = stringBuilder.Replace("\\u003c", "<");
-                               stringBuilder = stringBuilder.Replace("\\u003e", ">");
-                               stringBuilder = stringBuilder.Replace("\\\\", "\\");
-
-                               return System.Web.HttpUtility.UrlDecode(stringBuilder.ToString());
-               }
-                       else {
-                               throw new Exception((match.Groups.Count > REGEX_MATCH_INDEX_TWO_VALUE ? 
match.Groups[REGEX_MATCH_INDEX_TWO_VALUE].Value + ": " : String.Empty) + (match.Groups.Count > 
REGEX_MATCH_INDEX_ONE_VALUE ? match.Groups[REGEX_MATCH_INDEX_ONE_VALUE].Value : String.Empty));
-                       }
-               }
-
-    }
-}
\ No newline at end of file
+// Commenting this class. Not used as the Google Translate API no longer allows for free access.
+///*
+// * This file is part of SubLib.
+// * Copyright (C) 2011 Pedro Castro
+// *
+// * SubLib is free software; you can redistribute it and/or modify
+// * it under the terms of the GNU General Public License as published by
+// * the Free Software Foundation; either version 2 of the License, or
+// * (at your option) any later version.
+// *
+// * SubLib is distributed in the hope that it will be useful,
+// * but WITHOUT ANY WARRANTY; without even the implied warranty of
+// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// * GNU General Public License for more details.
+// *
+// * You should have received a copy of the GNU General Public License
+// * along with this program; if not, write to the Free Software
+// * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+// */
+
+//using SubLib.Core.Domain;
+//using SubLib.Exceptions;
+//using System;
+//using System.Net;
+//using System.IO;
+//using System.Globalization;
+//using System.Text.RegularExpressions;
+//using System.Text;
+
+//namespace SubLib.Core {
+
+//     /// <summary>Allows translating subtitles from one language to another using Google Translate 
service.</summary>
+//     public class Translator {
+//             private const string REQUEST_URL_FORMAT = 
"http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&{0}langpair={1}|{2}";
+//             private const string REQUEST_LINE_FORMAT = "q={0}&";
+
+//             private const char SPLIT_CHAR = '\n';
+//             private const char CULTURE_REPLACEE = '_';
+//             private const char CULTURE_REPLACER = '-';
+
+//             private const string JSON_RESPONSE_SUCCESS = "200";
+
+//             private const string REGEX_ERROR_MATCH = @"^.*\""responseDetails\"": 
(.+),.*\""responseStatus\"":.*([0-9][0-9][0-9]).*$";
+//             private const string REGEX_RESPONSE_MATCH = @"\""translatedText\"":\""([^\""]*)";
+//             private const int REGEX_MATCH_INDEX_ONE_VALUE = 1;
+//             private const int REGEX_MATCH_INDEX_TWO_VALUE = 2;
+
+//             public const int TIMEOUT = 3000;
+
+
+//             /* Public methods */
+
+//             /// <summary>Translates given text between two given languages.</summary>
+//             public static string TranslateText (string inputText, string fromLanguage, string toLanguage, 
int timeoutMillis) {
+//                     // testing emptiness of the string
+//                     if (inputText.Trim().Length == 0)
+//                             return String.Empty;
+
+//                     // splitting input text into single lines; line-breaks cannot be transferred to 
Google Translate
+//                     StringBuilder stringBuilder = new StringBuilder();
+//                     foreach (String split in inputText.Split(SPLIT_CHAR)) {
+//                             stringBuilder.Append(String.Format(REQUEST_LINE_FORMAT, 
System.Web.HttpUtility.UrlEncode(split)));
+//                     }
+
+//                     try {
+//                 //TODO 'key' parameter could be added
+//                             // building request URL
+//                             string requestUrl = String.Format(REQUEST_URL_FORMAT, 
stringBuilder.ToString(),
+//                     CultureInfo.CreateSpecificCulture(fromLanguage.Replace(CULTURE_REPLACEE, 
CULTURE_REPLACER)).TwoLetterISOLanguageName.ToLowerInvariant(),
+//                                 CultureInfo.CreateSpecificCulture(toLanguage.Replace(CULTURE_REPLACEE, 
CULTURE_REPLACER)).TwoLetterISOLanguageName.ToLowerInvariant()
+//                 );
+
+//                             // translating
+//                 HttpWebRequest req = HttpWebRequest.Create(requestUrl) as HttpWebRequest;
+//                             req.Timeout = timeoutMillis;
+//                             req.Method = WebRequestMethods.Http.Get;
+//                HttpWebResponse res = req.GetResponse() as HttpWebResponse;
+
+//                             // processing response
+//                string responseJson = new StreamReader(res.GetResponseStream()).ReadToEnd();
+
+//                return ProcessJson(responseJson);
+//            }
+//                     catch (Exception e) {
+//                             throw new TranslatorException(e.Message);
+//            }
+//        }
+
+
+//             /* Private methods */
+
+//             /// <summary>Processes JSON response from Google Translate service.</summary>
+//             private static string ProcessJson (string responseJson) {
+//                     // fixing english-related quote problem
+//                     responseJson = responseJson.Replace("\\\"", "\\u0026quot;");
+
+//                     // matching responseStatus
+//                     StringBuilder stringBuilder = new StringBuilder();
+//                     Match match = Regex.Match(responseJson, REGEX_ERROR_MATCH, RegexOptions.IgnoreCase | 
RegexOptions.Compiled);
+//                     if (match.Success && match.Groups.Count > REGEX_MATCH_INDEX_TWO_VALUE && 
match.Groups[REGEX_MATCH_INDEX_TWO_VALUE].Value == JSON_RESPONSE_SUCCESS) {
+
+//                             // matching multi-line translated text and building output
+//                             bool first = true;
+//                 MatchCollection matchCollection = Regex.Matches(responseJson, REGEX_RESPONSE_MATCH, 
RegexOptions.IgnoreCase | RegexOptions.Compiled);
+//                             foreach (Match textMatch in matchCollection) {
+//                                     if (textMatch.Success && textMatch.Groups.Count > 
REGEX_MATCH_INDEX_ONE_VALUE) {
+//                                             if (!first)
+//                                                     stringBuilder.Append(SPLIT_CHAR);
+
+//                                             
stringBuilder.Append(textMatch.Groups[REGEX_MATCH_INDEX_ONE_VALUE].Value);
+//                                             first = false;
+//                                     }
+//                             }
+
+//                             // replacing escaped characters that are not decoded automatically
+//                             stringBuilder = stringBuilder.Replace("\\u0026#39", "'");
+//                             stringBuilder = stringBuilder.Replace("\\u0026quot;", "\"");
+//                             stringBuilder = stringBuilder.Replace("\\u0026amp;", "&");
+//                             stringBuilder = stringBuilder.Replace("\\u0026lt;", "<");
+//                             stringBuilder = stringBuilder.Replace("\\u0026qt;", ">");
+//                             stringBuilder = stringBuilder.Replace("\\u0026amp;", "&");
+//                             stringBuilder = stringBuilder.Replace("\\u0026", "&");
+//                             stringBuilder = stringBuilder.Replace("\\u003c", "<");
+//                             stringBuilder = stringBuilder.Replace("\\u003e", ">");
+//                             stringBuilder = stringBuilder.Replace("\\\\", "\\");
+
+//                             return System.Web.HttpUtility.UrlDecode(stringBuilder.ToString());
+//             }
+//                     else {
+//                             throw new Exception((match.Groups.Count > REGEX_MATCH_INDEX_TWO_VALUE ? 
match.Groups[REGEX_MATCH_INDEX_TWO_VALUE].Value + ": " : String.Empty) + (match.Groups.Count > 
REGEX_MATCH_INDEX_ONE_VALUE ? match.Groups[REGEX_MATCH_INDEX_ONE_VALUE].Value : String.Empty));
+//                     }
+//             }
+
+//    }
+//}
\ No newline at end of file


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]