1 // OpenTween - Client of Twitter
2 // Copyright (c) 2016 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
5 // This file is part of OpenTween.
7 // This program is free software; you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 3 of the License, or (at your option)
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 // You should have received a copy of the GNU General Public License along
18 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
19 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 // Boston, MA 02110-1301, USA.
23 using System.Collections.Generic;
25 using System.Net.Http;
26 using System.Net.Http.Headers;
27 using System.Runtime.Serialization.Json;
29 using System.Threading.Tasks;
31 using System.Xml.Linq;
32 using System.Xml.XPath;
33 using OpenTween.Connection;
35 namespace OpenTween.Api
37 public class MicrosoftTranslatorApi
39 public static readonly Uri IssueTokenEndpoint = new Uri("https://api.cognitive.microsoft.com/sts/v1.0/issueToken");
40 public static readonly Uri TranslateEndpoint = new Uri("https://api.cognitive.microsofttranslator.com/translate");
42 public string AccessToken { get; internal set; }
43 public DateTimeUtc RefreshAccessTokenAt { get; internal set; }
45 private HttpClient Http => this.localHttpClient ?? Networking.Http;
46 private readonly HttpClient localHttpClient;
48 public MicrosoftTranslatorApi()
53 public MicrosoftTranslatorApi(HttpClient http)
54 => this.localHttpClient = http;
56 public async Task<string> TranslateAsync(string text, string langTo, string langFrom = null)
58 await this.UpdateAccessTokenIfExpired()
59 .ConfigureAwait(false);
61 var param = new Dictionary<string, string>
63 ["api-version"] = "3.0",
68 param["from"] = langFrom;
70 var requestUri = new Uri(TranslateEndpoint, "?" + MyCommon.BuildQueryString(param));
72 using (var request = new HttpRequestMessage(HttpMethod.Post, requestUri))
74 request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken);
76 var escapedText = JsonUtils.EscapeJsonString(text);
77 var json = $@"[{{""Text"": ""{escapedText}""}}]";
79 using (var body = new StringContent(json, Encoding.UTF8, "application/json"))
81 request.Content = body;
83 using (var response = await this.Http.SendAsync(request).ConfigureAwait(false))
85 response.EnsureSuccessStatusCode();
87 var responseJson = await response.Content.ReadAsByteArrayAsync()
88 .ConfigureAwait(false);
90 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(responseJson, XmlDictionaryReaderQuotas.Max))
92 var xElm = XElement.Load(jsonReader);
93 var transtlationTextElm = xElm.XPathSelectElement("/item/translations/item/text[1]");
95 return transtlationTextElm?.Value ?? "";
102 public async Task UpdateAccessTokenIfExpired()
104 if (this.AccessToken != null && this.RefreshAccessTokenAt > DateTimeUtc.Now)
107 var (accessToken, expiresIn) = await this.GetAccessTokenAsync()
108 .ConfigureAwait(false);
110 this.AccessToken = accessToken;
112 // アクセストークンの実際の有効期限より 30 秒早めに失効として扱う
113 this.RefreshAccessTokenAt = DateTimeUtc.Now + expiresIn - TimeSpan.FromSeconds(30);
116 internal virtual async Task<(string AccessToken, TimeSpan ExpiresIn)> GetAccessTokenAsync()
118 using (var request = new HttpRequestMessage(HttpMethod.Post, IssueTokenEndpoint))
120 request.Headers.Add("Ocp-Apim-Subscription-Key", ApplicationSettings.TranslatorSubscriptionKey);
122 using (var response = await this.Http.SendAsync(request).ConfigureAwait(false))
124 var accessToken = await response.Content.ReadAsStringAsync()
125 .ConfigureAwait(false);
127 return (accessToken, TimeSpan.FromMinutes(10));