diff --git a/browser/components/translation/BingTranslator.jsm b/browser/components/translation/BingTranslator.jsm index ae2760d51de2..0efb5a1d73a1 100644 --- a/browser/components/translation/BingTranslator.jsm +++ b/browser/components/translation/BingTranslator.jsm @@ -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 = + '' + + '' + + '' + this.sourceLanguage + '' + + '' + + 'text/html' + + '' + + '' + + ''; + + for (let [, text] of this.translationData) { + requestString += '' + text + ''; + } + + requestString += '' + + '' + this.targetLanguage + '' + + ''; + + 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. */