Bug 971054 - Part 3. BingRequest class that represents one network request sent to translation service. r=florian

This commit is contained in:
Felipe Gomes 2014-05-19 17:28:25 -03:00
Родитель 3accdb2bac
Коммит 88fad51371
1 изменённых файлов: 71 добавлений и 0 удалений

Просмотреть файл

@ -13,6 +13,7 @@ Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-common/rest.js");
// The maximum amount of net data allowed per request on Bing's API.
const MAX_REQUEST_DATA = 5000; // Documentation says 10000 but anywhere
@ -176,6 +177,76 @@ this.BingTranslation.prototype = {
}
};
/**
* Represents a request (for 1 chunk) sent off to Bing's service.
*
* @params translationData The data to be used for this translation,
* generated by the generateNextTranslationRequest...
* function.
* @param sourceLanguage The source language of the document.
* @param targetLanguage The target language for the translation.
*
*/
function BingRequest(translationData, sourceLanguage, targetLanguage) {
this.translationData = translationData;
this.sourceLanguage = sourceLanguage;
this.targetLanguage = targetLanguage;
}
BingRequest.prototype = {
/**
* Initiates the request
*/
fireRequest: function() {
return Task.spawn(function *(){
let token = yield BingTokenManager.getToken();
let auth = "Bearer " + token;
let request = new RESTRequest("https://api.microsofttranslator.com/v2/Http.svc/TranslateArray");
request.setHeader("Content-type", "text/xml");
request.setHeader("Authorization", auth);
let requestString =
'<TranslateArrayRequest>' +
'<AppId/>' +
'<From>' + this.sourceLanguage + '</From>' +
'<Options>' +
'<ContentType xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">text/html</ContentType>' +
'<ReservedFlags xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" />' +
'</Options>' +
'<Texts xmlns:s="http://schemas.microsoft.com/2003/10/Serialization/Arrays">';
for (let [, text] of this.translationData) {
requestString += '<s:string>' + text + '</s:string>';
}
requestString += '</Texts>' +
'<To>' + this.targetLanguage + '</To>' +
'</TranslateArrayRequest>';
let utf8 = CommonUtils.encodeUTF8(requestString);
let deferred = Promise.defer();
request.post(utf8, function(err) {
deferred.resolve(this);
}.bind(this));
this.networkRequest = request;
return deferred.promise;
}.bind(this));
},
/**
* Checks if the request succeeded. Only valid
* after the request has finished.
*
* @returns True if the request succeeded.
*/
get requestSucceeded() {
return !this.networkRequest.error &&
this.networkRequest.response.success;
}
};
/**
* Escape a string to be valid XML content.
*/