Advertisement
goodgrimes

SAMP Translator Source

May 4th, 2012
1,233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.82 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. using System.Runtime.Serialization.Json;
  8. using System.Runtime.Serialization;
  9. using System.Web;
  10. using System.ServiceModel.Channels;
  11. using System.ServiceModel;
  12. using System.Diagnostics;
  13. using System.Runtime.InteropServices;
  14. using System.Threading;
  15. using System.Windows.Forms;
  16.  
  17. namespace SAMP_Translator
  18. {
  19.     class Program
  20.     {
  21.  
  22.         [STAThread]
  23.         static void Main(string[] args)
  24.         {
  25.             TranslatorService.LanguageServiceClient client = new TranslatorService.LanguageServiceClient();
  26.             Console.WriteLine("SAMP Translator 1.0 by goodgrimes. Read the read-me for more information");
  27.             Console.WriteLine("on how to properly configure this program. If you have any questions or");
  28.             Console.WriteLine("suggestions, send them to goodgrimes@gmail.com. Enjoy!");
  29.             Console.WriteLine(" ");
  30.             Console.WriteLine(" ");
  31.             Console.WriteLine(" ");
  32.             AdmAccessToken admToken;
  33.             Stopwatch stopwatch = new Stopwatch();
  34.             Console.Title = "SAMP Translator by goodgrimes";
  35.             string plainText = null;
  36.             string preTrans = null;
  37.             string clientName = null;
  38.             string secretKey = null;
  39.             string language = null;
  40.             string logDir = null;
  41.             string reTrans = null;
  42.             string dialogPrec = null;
  43.             string reverTrans = null;
  44.             string revTransProxy = null; //To remember the last reverse translation done so it doesn't loop infinitely
  45.             FileInfo config = new FileInfo(@"config.cfg");
  46.  
  47.             StreamReader configRead = config.OpenText();
  48.  
  49.             clientName = configRead.ReadLine();
  50.             secretKey = configRead.ReadLine();
  51.             language = configRead.ReadLine();
  52.             reTrans = configRead.ReadLine();
  53.             logDir = configRead.ReadLine();
  54.             dialogPrec = configRead.ReadLine();
  55.             reverTrans = configRead.ReadLine();
  56.            
  57.             FileStream filestream = new FileStream(@logDir, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  58.             StreamReader reader = new StreamReader(filestream);
  59.  
  60.             AdmAuthentication admAuth = new AdmAuthentication(clientName, secretKey);
  61.             reader.ReadToEnd();
  62.             string tempText; //Holds the ReadLine() since it can only be called once per translation
  63.             admToken = admAuth.GetAccessToken();
  64.             stopwatch.Start();
  65.             do
  66.             {
  67.  
  68.                 if ((Clipboard.ContainsText() == true) && (Clipboard.GetText(TextDataFormat.Text) != revTransProxy))  //Checks the clipboard for text to be translated
  69.                 {
  70.  
  71.                     string revTransTextRaw = Clipboard.GetText(TextDataFormat.Text);;
  72.                     int transDivide = (revTransTextRaw.IndexOf(reverTrans));
  73.                     if (transDivide != -1)
  74.                     {
  75.                         string revTransText = revTransTextRaw.Substring(transDivide + reverTrans.Length); //Removes the reverse translation pre-cursor and stores the text to be translated
  76.                         revTransProxy = revTransTextRaw;
  77.                         Console.WriteLine("Translating text...");
  78.                         revTransTextRaw = client.Translate(("Bearer " + admToken.access_token), revTransText, "", reTrans, "text/plain", "general");
  79.                         Clipboard.SetText(revTransTextRaw);
  80.                         Console.WriteLine("Translation complete!");
  81.                 }
  82.                 }
  83.  
  84.  
  85.                 if (stopwatch.ElapsedMilliseconds >= 600000) // A new token is required every 10 minutes.
  86.                 {
  87.                     Thread.Sleep(5000);
  88.                     admToken = admAuth.GetAccessToken();
  89.                     stopwatch.Reset();
  90.                 }
  91.                 tempText = reader.ReadLine();
  92.  
  93.  
  94.  
  95.                 if (tempText != null)
  96.                 {
  97.                     try
  98.                     {
  99.                         int dialogDivide = tempText.IndexOf(dialogPrec);
  100.                         if (dialogDivide != -1)
  101.                         {
  102.                             plainText = tempText.Substring(dialogDivide);
  103.                             preTrans = tempText.Substring(0, dialogDivide);
  104.                             string transText = null;
  105.  
  106.  
  107.  
  108.                             if (((DetectLang(admToken.access_token, plainText)) != language))
  109.                             { //Checks if the language attempted to be translated is the native language set
  110.  
  111.                                 transText = client.Translate(("Bearer " + admToken.access_token), plainText, "", language, "text/plain", "general");//Translation positive
  112.                             }
  113.                             else
  114.                                 transText = plainText; //Changes the transText to untranslated original in the event that the attempted translation wasn't valid
  115.  
  116.  
  117.                             Console.WriteLine(preTrans + transText);
  118.                         }
  119.                     }
  120.                     catch (Exception e) //If the text isn't detected as any language, it's simply printed
  121.                     {
  122.                         Console.WriteLine(preTrans + plainText);
  123.                         Console.WriteLine(e.Message);
  124.                     }
  125.                 };
  126.             }
  127.             while (true);
  128.         }
  129.  
  130.         public static string DetectLang(string authToken, string textToDetect)
  131.         {
  132.             //Keep appId parameter blank as we are sending access token in authorization header.
  133.             string uri = "http://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + textToDetect;
  134.             HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
  135.             httpWebRequest.Headers.Add("Authorization", "Bearer " + authToken);
  136.             WebResponse response = null;
  137.             response = httpWebRequest.GetResponse();
  138.             using (Stream stream = response.GetResponseStream())
  139.             {
  140.                 System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
  141.                 string languageDetected = (string)dcs.ReadObject(stream);
  142.                 return languageDetected;
  143.             }
  144.  
  145.         }
  146.  
  147.         [DataContract]
  148.         public class AdmAuthentication
  149.         {
  150.             public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
  151.             private string clientId;
  152.             private string cientSecret;
  153.             private string request;
  154.  
  155.             public AdmAuthentication(string clientId, string clientSecret)
  156.             {
  157.                 this.clientId = clientId;
  158.                 this.cientSecret = clientSecret;
  159.                 //If clientid or client secret has special characters, encode before sending request
  160.                 this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret));
  161.             }
  162.  
  163.             public AdmAccessToken GetAccessToken()
  164.             {
  165.                 return HttpPost(DatamarketAccessUri, this.request);
  166.             }
  167.  
  168.             private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
  169.             {
  170.                 //Prepare OAuth request
  171.                 WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
  172.                 webRequest.ContentType = "application/x-www-form-urlencoded";
  173.                 webRequest.Method = "POST";
  174.                 byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
  175.                 webRequest.ContentLength = bytes.Length;
  176.                 using (Stream outputStream = webRequest.GetRequestStream())
  177.                 {
  178.                     outputStream.Write(bytes, 0, bytes.Length);
  179.                 }
  180.                 using (WebResponse webResponse = webRequest.GetResponse())
  181.                 {
  182.                     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
  183.                     //Get deserialized object from JSON stream
  184.                     AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
  185.                     return token;
  186.                 }
  187.             }
  188.         }
  189.     }
  190.  
  191.     public class AdmAccessToken
  192.     {
  193.         [DataMember]
  194.         public string access_token { get; set; }
  195.         [DataMember]
  196.         public string token_type { get; set; }
  197.         [DataMember]
  198.         public string expires_in { get; set; }
  199.         [DataMember]
  200.         public string scope { get; set; }
  201.     }
  202. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement