From b2e3b8de16de551516b13fff493c01bb4a61f25c Mon Sep 17 00:00:00 2001 From: Ricardo Espinoza Date: Thu, 22 Oct 2020 05:36:42 -0400 Subject: [PATCH] :sparkles: Add Google Translate node (#1086) * :sparkles: Add Google Translate node * :hammer: Add autoload for target languages * :zap: Small improvements Co-authored-by: Tanay Pant --- .../GoogleTranslateOAuth2Api.credentials.ts | 25 +++ .../Google/Translate/GenericFunctions.ts | 128 ++++++++++++ .../Google/Translate/GoogleTranslate.node.ts | 194 ++++++++++++++++++ .../Google/Translate/googletranslate.svg | 35 ++++ packages/nodes-base/package.json | 2 + 5 files changed, 384 insertions(+) create mode 100644 packages/nodes-base/credentials/GoogleTranslateOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/nodes/Google/Translate/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/Google/Translate/GoogleTranslate.node.ts create mode 100644 packages/nodes-base/nodes/Google/Translate/googletranslate.svg diff --git a/packages/nodes-base/credentials/GoogleTranslateOAuth2Api.credentials.ts b/packages/nodes-base/credentials/GoogleTranslateOAuth2Api.credentials.ts new file mode 100644 index 0000000000..0cdcd608e0 --- /dev/null +++ b/packages/nodes-base/credentials/GoogleTranslateOAuth2Api.credentials.ts @@ -0,0 +1,25 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +const scopes = [ + 'https://www.googleapis.com/auth/cloud-translation', +]; + +export class GoogleTranslateOAuth2Api implements ICredentialType { + name = 'googleTranslateOAuth2Api'; + extends = [ + 'googleOAuth2Api', + ]; + displayName = 'Google Translate OAuth2 API'; + documentationUrl = 'google'; + properties = [ + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: scopes.join(' '), + }, + ]; +} diff --git a/packages/nodes-base/nodes/Google/Translate/GenericFunctions.ts b/packages/nodes-base/nodes/Google/Translate/GenericFunctions.ts new file mode 100644 index 0000000000..2cf1a47c0a --- /dev/null +++ b/packages/nodes-base/nodes/Google/Translate/GenericFunctions.ts @@ -0,0 +1,128 @@ +import { + OptionsWithUri, +} from 'request'; + +import { + IExecuteFunctions, + IExecuteSingleFunctions, + ILoadOptionsFunctions, +} from 'n8n-core'; + +import { + IDataObject, +} from 'n8n-workflow'; + +import * as moment from 'moment-timezone'; + +import * as jwt from 'jsonwebtoken'; + +export async function googleApiRequest(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, headers: IDataObject = {}): Promise { // tslint:disable-line:no-any + const authenticationMethod = this.getNodeParameter('authentication', 0, 'serviceAccount') as string; + const options: OptionsWithUri = { + headers: { + 'Content-Type': 'application/json', + }, + method, + body, + qs, + uri: uri || `https://translation.googleapis.com${resource}`, + json: true + }; + try { + if (Object.keys(headers).length !== 0) { + options.headers = Object.assign({}, options.headers, headers); + } + if (Object.keys(body).length === 0) { + delete options.body; + } + + if (authenticationMethod === 'serviceAccount') { + const credentials = this.getCredentials('googleApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + const { access_token } = await getAccessToken.call(this, credentials as IDataObject); + + options.headers!.Authorization = `Bearer ${access_token}`; + //@ts-ignore + return await this.helpers.request(options); + } else { + //@ts-ignore + return await this.helpers.requestOAuth2.call(this, 'googleTranslateOAuth2Api', options); + } + } catch (error) { + if (error.response && error.response.body && error.response.body.message) { + // Try to return the error prettier + throw new Error(`Google Translate error response [${error.statusCode}]: ${error.response.body.message}`); + } + throw error; + } +} + +export async function googleApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, propertyName: string, method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise { // tslint:disable-line:no-any + + const returnData: IDataObject[] = []; + + let responseData; + query.maxResults = 100; + + do { + responseData = await googleApiRequest.call(this, method, endpoint, body, query); + query.pageToken = responseData['nextPageToken']; + returnData.push.apply(returnData, responseData[propertyName]); + } while ( + responseData['nextPageToken'] !== undefined && + responseData['nextPageToken'] !== '' + ); + + return returnData; +} + +function getAccessToken(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, credentials: IDataObject): Promise { + //https://developers.google.com/identity/protocols/oauth2/service-account#httprest + + const scopes = [ + 'https://www.googleapis.com/auth/cloud-translation', + 'https://www.googleapis.com/auth/cloud-platform', + ]; + + const now = moment().unix(); + + const signature = jwt.sign( + { + 'iss': credentials.email as string, + 'sub': credentials.email as string, + 'scope': scopes.join(' '), + 'aud': `https://oauth2.googleapis.com/token`, + 'iat': now, + 'exp': now + 3600, + }, + credentials.privateKey as string, + { + algorithm: 'RS256', + header: { + 'kid': credentials.privateKey as string, + 'typ': 'JWT', + 'alg': 'RS256', + }, + } + ); + + const options: OptionsWithUri = { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + method: 'POST', + form: { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: signature, + }, + uri: 'https://oauth2.googleapis.com/token', + json: true + }; + + //@ts-ignore + return this.helpers.request(options); +} diff --git a/packages/nodes-base/nodes/Google/Translate/GoogleTranslate.node.ts b/packages/nodes-base/nodes/Google/Translate/GoogleTranslate.node.ts new file mode 100644 index 0000000000..50f6a61fa3 --- /dev/null +++ b/packages/nodes-base/nodes/Google/Translate/GoogleTranslate.node.ts @@ -0,0 +1,194 @@ + +import { + IExecuteFunctions, +} from 'n8n-core'; + +import { + ILoadOptionsFunctions, + INodeExecutionData, + INodePropertyOptions, + INodeType, + INodeTypeDescription, +} from 'n8n-workflow'; + +import { + googleApiRequest, +} from './GenericFunctions'; + +export interface IGoogleAuthCredentials { + email: string; + privateKey: string; +} + +export class GoogleTranslate implements INodeType { + description: INodeTypeDescription = { + displayName: 'Google Translate', + name: 'googleTranslate', + icon: 'file:googletranslate.svg', + group: ['input', 'output'], + version: 1, + description: 'Translate data using Google Translate', + subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', + defaults: { + name: 'Google Translate', + color: '#5390f5', + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'googleApi', + required: true, + displayOptions: { + show: { + authentication: [ + 'serviceAccount', + ], + }, + }, + }, + { + name: 'googleTranslateOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, + ], + properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Service Account', + value: 'serviceAccount', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'serviceAccount', + }, + { + displayName: 'Resource', + name: 'resource', + type: 'options', + options: [ + { + name: 'Language', + value: 'language', + }, + ], + default: 'language', + description: 'The operation to perform', + }, + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'language', + ], + }, + }, + options: [ + { + name: 'Translate', + value: 'translate', + description: 'Translate data', + }, + ], + default: 'translate', + description: 'The operation to perform', + }, + // ---------------------------------- + // All + // ---------------------------------- + { + displayName: 'Query', + name: 'query', + type: 'string', + default: '', + description: 'The input text to translate', + required: true, + displayOptions: { + show: { + operation: [ + 'translate', + ], + }, + }, + }, + { + displayName: 'Translate To', + name: 'translateTo', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getLanguages', + }, + default: '', + description: 'The language to use for translation of the input text, set to one of the
language codes listed in Language Support', + required: true, + displayOptions: { + show: { + operation: [ + 'translate', + ], + }, + }, + }, + ], + }; + + methods = { + loadOptions: { + async getLanguages( + this: ILoadOptionsFunctions + ): Promise { + const returnData: INodePropertyOptions[] = []; + const { data: { languages } } = await googleApiRequest.call( + this, + 'GET', + '/language/translate/v2/languages' + ); + for (const language of languages) { + returnData.push({ + name: language.language.toUpperCase(), + value: language.language + }); + } + return returnData; + }, + } + }; + + async execute(this: IExecuteFunctions): Promise { + const items = this.getInputData(); + const length = items.length as unknown as number; + + const resource = this.getNodeParameter('resource', 0) as string; + const operation = this.getNodeParameter('operation', 0) as string; + const responseData = []; + for (let i = 0; i < length; i++) { + if (resource === 'language') { + if (operation === 'translate') { + const query = this.getNodeParameter('query', i) as string; + const translateTo = this.getNodeParameter('translateTo', i) as string; + + const response = await googleApiRequest.call(this, 'POST', `/language/translate/v2`, { q: query, target: translateTo }); + responseData.push(response.data.translations[0]); + } + } + } + return [this.helpers.returnJsonArray(responseData)]; + } +} diff --git a/packages/nodes-base/nodes/Google/Translate/googletranslate.svg b/packages/nodes-base/nodes/Google/Translate/googletranslate.svg new file mode 100644 index 0000000000..798804dc4b --- /dev/null +++ b/packages/nodes-base/nodes/Google/Translate/googletranslate.svg @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/packages/nodes-base/package.json b/packages/nodes-base/package.json index 8f0461ceca..22a9470715 100644 --- a/packages/nodes-base/package.json +++ b/packages/nodes-base/package.json @@ -82,6 +82,7 @@ "dist/credentials/GoogleSheetsOAuth2Api.credentials.js", "dist/credentials/GSuiteAdminOAuth2Api.credentials.js", "dist/credentials/GoogleTasksOAuth2Api.credentials.js", + "dist/credentials/GoogleTranslateOAuth2Api.credentials.js", "dist/credentials/YouTubeOAuth2Api.credentials.js", "dist/credentials/GumroadApi.credentials.js", "dist/credentials/HarvestApi.credentials.js", @@ -273,6 +274,7 @@ "dist/nodes/Google/GSuiteAdmin/GSuiteAdmin.node.js", "dist/nodes/Google/Sheet/GoogleSheets.node.js", "dist/nodes/Google/Task/GoogleTasks.node.js", + "dist/nodes/Google/Translate/GoogleTranslate.node.js", "dist/nodes/Google/YouTube/YouTube.node.js", "dist/nodes/GraphQL/GraphQL.node.js", "dist/nodes/Gumroad/GumroadTrigger.node.js",