Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.IO;
- using System.Runtime.Serialization.Json;
- using System.Runtime.Serialization;
- using System.Web;
- using System.ServiceModel.Channels;
- using System.ServiceModel;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Threading;
- using System.Windows.Forms;
- namespace SAMP_Translator
- {
- class Program
- {
- [STAThread]
- static void Main(string[] args)
- {
- TranslatorService.LanguageServiceClient client = new TranslatorService.LanguageServiceClient();
- Console.WriteLine("SAMP Translator 1.0 by goodgrimes. Read the read-me for more information");
- Console.WriteLine("on how to properly configure this program. If you have any questions or");
- Console.WriteLine("suggestions, send them to goodgrimes@gmail.com. Enjoy!");
- Console.WriteLine(" ");
- Console.WriteLine(" ");
- Console.WriteLine(" ");
- AdmAccessToken admToken;
- Stopwatch stopwatch = new Stopwatch();
- Console.Title = "SAMP Translator by goodgrimes";
- string plainText = null;
- string preTrans = null;
- string clientName = null;
- string secretKey = null;
- string language = null;
- string logDir = null;
- string reTrans = null;
- string dialogPrec = null;
- string reverTrans = null;
- string revTransProxy = null; //To remember the last reverse translation done so it doesn't loop infinitely
- FileInfo config = new FileInfo(@"config.cfg");
- StreamReader configRead = config.OpenText();
- clientName = configRead.ReadLine();
- secretKey = configRead.ReadLine();
- language = configRead.ReadLine();
- reTrans = configRead.ReadLine();
- logDir = configRead.ReadLine();
- dialogPrec = configRead.ReadLine();
- reverTrans = configRead.ReadLine();
- FileStream filestream = new FileStream(@logDir, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
- StreamReader reader = new StreamReader(filestream);
- AdmAuthentication admAuth = new AdmAuthentication(clientName, secretKey);
- reader.ReadToEnd();
- string tempText; //Holds the ReadLine() since it can only be called once per translation
- admToken = admAuth.GetAccessToken();
- stopwatch.Start();
- do
- {
- if ((Clipboard.ContainsText() == true) && (Clipboard.GetText(TextDataFormat.Text) != revTransProxy)) //Checks the clipboard for text to be translated
- {
- string revTransTextRaw = Clipboard.GetText(TextDataFormat.Text);;
- int transDivide = (revTransTextRaw.IndexOf(reverTrans));
- if (transDivide != -1)
- {
- string revTransText = revTransTextRaw.Substring(transDivide + reverTrans.Length); //Removes the reverse translation pre-cursor and stores the text to be translated
- revTransProxy = revTransTextRaw;
- Console.WriteLine("Translating text...");
- revTransTextRaw = client.Translate(("Bearer " + admToken.access_token), revTransText, "", reTrans, "text/plain", "general");
- Clipboard.SetText(revTransTextRaw);
- Console.WriteLine("Translation complete!");
- }
- }
- if (stopwatch.ElapsedMilliseconds >= 600000) // A new token is required every 10 minutes.
- {
- Thread.Sleep(5000);
- admToken = admAuth.GetAccessToken();
- stopwatch.Reset();
- }
- tempText = reader.ReadLine();
- if (tempText != null)
- {
- try
- {
- int dialogDivide = tempText.IndexOf(dialogPrec);
- if (dialogDivide != -1)
- {
- plainText = tempText.Substring(dialogDivide);
- preTrans = tempText.Substring(0, dialogDivide);
- string transText = null;
- if (((DetectLang(admToken.access_token, plainText)) != language))
- { //Checks if the language attempted to be translated is the native language set
- transText = client.Translate(("Bearer " + admToken.access_token), plainText, "", language, "text/plain", "general");//Translation positive
- }
- else
- transText = plainText; //Changes the transText to untranslated original in the event that the attempted translation wasn't valid
- Console.WriteLine(preTrans + transText);
- }
- }
- catch (Exception e) //If the text isn't detected as any language, it's simply printed
- {
- Console.WriteLine(preTrans + plainText);
- Console.WriteLine(e.Message);
- }
- };
- }
- while (true);
- }
- public static string DetectLang(string authToken, string textToDetect)
- {
- //Keep appId parameter blank as we are sending access token in authorization header.
- string uri = "http://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + textToDetect;
- HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
- httpWebRequest.Headers.Add("Authorization", "Bearer " + authToken);
- WebResponse response = null;
- response = httpWebRequest.GetResponse();
- using (Stream stream = response.GetResponseStream())
- {
- System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
- string languageDetected = (string)dcs.ReadObject(stream);
- return languageDetected;
- }
- }
- [DataContract]
- public class AdmAuthentication
- {
- public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
- private string clientId;
- private string cientSecret;
- private string request;
- public AdmAuthentication(string clientId, string clientSecret)
- {
- this.clientId = clientId;
- this.cientSecret = clientSecret;
- //If clientid or client secret has special characters, encode before sending request
- 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));
- }
- public AdmAccessToken GetAccessToken()
- {
- return HttpPost(DatamarketAccessUri, this.request);
- }
- private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
- {
- //Prepare OAuth request
- WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
- webRequest.ContentType = "application/x-www-form-urlencoded";
- webRequest.Method = "POST";
- byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
- webRequest.ContentLength = bytes.Length;
- using (Stream outputStream = webRequest.GetRequestStream())
- {
- outputStream.Write(bytes, 0, bytes.Length);
- }
- using (WebResponse webResponse = webRequest.GetResponse())
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
- //Get deserialized object from JSON stream
- AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
- return token;
- }
- }
- }
- }
- public class AdmAccessToken
- {
- [DataMember]
- public string access_token { get; set; }
- [DataMember]
- public string token_type { get; set; }
- [DataMember]
- public string expires_in { get; set; }
- [DataMember]
- public string scope { get; set; }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement