Example #1
0
        private async Task <string> GetTranslationResult(HttpClient httpClient, string id)
        {
            var uri     = new Uri($"{Constants.MTCloudTranslateAPIUri}/v4" + $"/mt/translations/async/{id}/content");
            var request = new HttpRequestMessage(HttpMethod.Get, uri);

            ConnectionService.AddTraceHeader(request);

            var responseMessage = await httpClient.SendAsync(request);

            var response = await responseMessage.Content.ReadAsStringAsync();

            if (responseMessage.IsSuccessStatusCode)
            {
                return(response);
            }

            return(string.Empty);
        }
Example #2
0
        private async Task <HttpResponseMessage> SendFeedback(dynamic translationFeedback)
        {
            if (ConnectionService.Credential.ValidTo < DateTime.UtcNow)
            {
                // attempt one connection
                var success = ConnectionService.Connect(ConnectionService.Credential);
                if (!success.Item1)
                {
                    _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} " + $"{PluginResources.Message_Connection_token_has_expired}\n {ConnectionService.Credential.Token}");
                    throw new Exception(PluginResources.Message_Connection_token_has_expired);
                }
            }

            HttpResponseMessage responseMessage;

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + ConnectionService.Credential.Token);

                var uri     = new Uri($"{Constants.MTCloudTranslateAPIUri}/v4/accounts/{ConnectionService.Credential.AccountId}/feedback/translations");
                var request = new HttpRequestMessage(HttpMethod.Post, uri);
                ConnectionService.AddTraceHeader(request);

                var serializerSettings =
                    new JsonSerializerSettings {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                var content = JsonConvert.SerializeObject(translationFeedback, serializerSettings);

                request.Content = new StringContent(content, new UTF8Encoding(), "application/json");

                responseMessage = await httpClient.SendAsync(request);

                var response = await responseMessage.Content.ReadAsStringAsync();

                responseMessage.ReasonPhrase = response;

                _logger.Info(PluginResources.SendFeedbackResponseFromServer, responseMessage.StatusCode, response);
            }

            return(responseMessage);
        }
Example #3
0
        private void CheckConnection()
        {
            if (ConnectionService.Credential.ValidTo >= DateTime.UtcNow)
            {
                return;
            }

            // attempt one connection
            var success = ConnectionService.Connect(ConnectionService.Credential);

            if (success.Item1)
            {
                return;
            }

            _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} " +
                          $"{PluginResources.Message_Connection_token_has_expired}\n {ConnectionService.Credential.Token}");

            throw new Exception(PluginResources.Message_Connection_token_has_expired);
        }
Example #4
0
        public async Task <Segment[]> TranslateText(string text, LanguageMappingModel model)
        {
            if (string.IsNullOrEmpty(model?.SelectedModel?.Model))
            {
                throw new Exception(PluginResources.Message_No_model_selected);
            }

            if (ConnectionService.Credential.ValidTo < DateTime.UtcNow)
            {
                // attempt one connection
                var success = ConnectionService.Connect(ConnectionService.Credential);
                if (!success.Item1)
                {
                    _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} " + $"{PluginResources.Message_Connection_token_has_expired}\n {ConnectionService.Credential.Token}");
                    throw new Exception(PluginResources.Message_Connection_token_has_expired);
                }
            }

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + ConnectionService.Credential.Token);

                var uri     = new Uri($"{Constants.MTCloudTranslateAPIUri}/v4" + "/mt/translations/async");
                var request = new HttpRequestMessage(HttpMethod.Post, uri);
                ConnectionService.AddTraceHeader(request);

                var translationRequestModel = new TranslationRequest
                {
                    Input            = new[] { text },
                    SourceLanguageId = model.SelectedSource.CodeName,
                    TargetLanguageId = model.SelectedTarget.CodeName,
                    Model            = model.SelectedModel.Model,
                    InputFormat      = "xliff"
                };

                if (!model.SelectedDictionary.Name.Equals(PluginResources.Message_No_dictionary_available) &&
                    !model.SelectedDictionary.Name.Equals(PluginResources.Message_No_dictionary))
                {
                    translationRequestModel.Dictionaries = new[] { model.SelectedDictionary?.DictionaryId };
                }

                var content = JsonConvert.SerializeObject(translationRequestModel);
                request.Content = new StringContent(content, new UTF8Encoding(), "application/json");

                var responseMessage = await httpClient.SendAsync(request);

                var response = await responseMessage.Content.ReadAsStringAsync();

                if (!responseMessage.IsSuccessStatusCode)
                {
                    return(null);
                }

                if (!(JsonConvert.DeserializeObject <TranslationResponse>(response) is TranslationResponse translationResponse))
                {
                    return(null);
                }

                var dataResponse = await GetTranslations(httpClient, translationResponse.RequestId);

                if (!(JsonConvert.DeserializeObject <TranslationResponse>(dataResponse) is TranslationResponse translations))
                {
                    return(null);
                }

                var translation = translations.Translation.FirstOrDefault();
                if (translation == null)
                {
                    return(null);
                }

                var translatedXliff = Converter.ParseXliffString(translation);
                if (translatedXliff == null)
                {
                    return(null);
                }

                var targetSegments = translatedXliff.GetTargetSegments(out var sourceSegments);

                OnTranslationReceived(sourceSegments, targetSegments.Select(seg => seg.ToString()).ToList());
                return(targetSegments);
            }
        }