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.
25 using System.Collections.Generic;
27 using System.Net.Http;
28 using System.Net.Http.Headers;
29 using System.Runtime.Serialization.Json;
31 using System.Threading.Tasks;
33 using System.Xml.Linq;
34 using System.Xml.XPath;
35 using OpenTween.Connection;
37 namespace OpenTween.Api
39 public class MicrosoftTranslatorApi
41 public static readonly Uri IssueTokenEndpoint = new Uri("https://api.cognitive.microsoft.com/sts/v1.0/issueToken");
42 public static readonly Uri TranslateEndpoint = new Uri("https://api.cognitive.microsofttranslator.com/translate");
44 public string AccessToken { get; internal set; } = "";
45 public DateTimeUtc RefreshAccessTokenAt { get; internal set; } = DateTimeUtc.MinValue;
47 private HttpClient Http => this.localHttpClient ?? Networking.Http;
48 private readonly HttpClient? localHttpClient;
50 public MicrosoftTranslatorApi()
55 public MicrosoftTranslatorApi(HttpClient? http)
56 => this.localHttpClient = http;
58 public async Task<string> TranslateAsync(string text, string langTo, string? langFrom = null)
60 await this.UpdateAccessTokenIfExpired()
61 .ConfigureAwait(false);
63 var param = new Dictionary<string, string>
65 ["api-version"] = "3.0",
70 param["from"] = langFrom;
72 var requestUri = new Uri(TranslateEndpoint, "?" + MyCommon.BuildQueryString(param));
74 using var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
75 request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken);
77 var escapedText = JsonUtils.EscapeJsonString(text);
78 var json = $@"[{{""Text"": ""{escapedText}""}}]";
80 using var body = new StringContent(json, Encoding.UTF8, "application/json");
81 request.Content = body;
83 using var response = await this.Http.SendAsync(request)
84 .ConfigureAwait(false);
86 response.EnsureSuccessStatusCode();
88 var responseJson = await response.Content.ReadAsByteArrayAsync()
89 .ConfigureAwait(false);
91 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 ?? "";
98 public async Task UpdateAccessTokenIfExpired()
100 if (!string.IsNullOrEmpty(this.AccessToken) && this.RefreshAccessTokenAt > DateTimeUtc.Now)
103 var (accessToken, expiresIn) = await this.GetAccessTokenAsync()
104 .ConfigureAwait(false);
106 this.AccessToken = accessToken;
108 // アクセストークンの実際の有効期限より 30 秒早めに失効として扱う
109 this.RefreshAccessTokenAt = DateTimeUtc.Now + expiresIn - TimeSpan.FromSeconds(30);
112 internal virtual async Task<(string AccessToken, TimeSpan ExpiresIn)> GetAccessTokenAsync()
114 using var request = new HttpRequestMessage(HttpMethod.Post, IssueTokenEndpoint);
115 request.Headers.Add("Ocp-Apim-Subscription-Key", ApplicationSettings.TranslatorSubscriptionKey);
117 using var response = await this.Http.SendAsync(request)
118 .ConfigureAwait(false);
120 var accessToken = await response.Content.ReadAsStringAsync()
121 .ConfigureAwait(false);
123 return (accessToken, TimeSpan.FromMinutes(10));