41 lines
1.5 KiB
C#
41 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Specialized;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace SpectacleTransformer {
|
|
|
|
public class GoogleTranslationRequest : HttpTranslationRequest {
|
|
public static Uri GoogleTranslateUrl = new Uri("https://translate.google.com/m");
|
|
|
|
// <3 https://stackoverflow.com/questions/1732348/#1732454
|
|
private static Regex ResultRegex = new Regex("<div class=\"result-container\">(?<result>[^<]*)</div>");
|
|
|
|
public GoogleTranslationRequest(Uri InstanceUri, Language Source, Language Target, string Text) : base(InstanceUri, Source, Target, Text) { }
|
|
|
|
public static new bool MatchesInstance(Uri InstanceUri) {
|
|
return GoogleTranslateUrl.Host == InstanceUri.Host;
|
|
}
|
|
|
|
public override Uri Url {
|
|
get {
|
|
NameValueCollection nvc = new NameValueCollection(3);
|
|
nvc["sl"] = Source.SourceName;
|
|
nvc["tl"] = Target.TargetName;
|
|
nvc["q"] = Text;
|
|
return new Uri(GoogleTranslateUrl, GoogleTranslateUrl.AbsolutePath + Utils.ToQueryString(nvc));
|
|
}
|
|
}
|
|
|
|
public override string DecodeResponse(string response) {
|
|
Match m = ResultRegex.Match(response);
|
|
if (m.Success && m.Groups["result"].Success) return m.Groups["result"].Value;
|
|
return null;
|
|
}
|
|
|
|
public override string DecodeErrorResponse(string responseBody) {
|
|
// I have no idea what Google Translate errors look like.
|
|
return null;
|
|
}
|
|
}
|
|
}
|