From 6105ba77162ed3ed8cc5eefde3597c1f2f4004d3 Mon Sep 17 00:00:00 2001 From: Nicolas Garnier Date: Tue, 30 Aug 2016 00:06:28 -0700 Subject: [PATCH] Update the message-translation Functions sample. Change-Id: I4967f01bbd3b6512e7605b05c6c23eac6eb72a42 --- message-translation/README.md | 38 ++++++------ message-translation/functions/index.js | 58 ++++++++++++++++++ message-translation/functions/package.json | 9 +++ message-translation/index.js | 71 ---------------------- message-translation/package.json | 8 --- minimal-webhook/functions/index.js | 2 +- 6 files changed, 86 insertions(+), 100 deletions(-) create mode 100644 message-translation/functions/index.js create mode 100644 message-translation/functions/package.json delete mode 100644 message-translation/index.js delete mode 100644 message-translation/package.json diff --git a/message-translation/README.md b/message-translation/README.md index 20a04c4..6ba7b05 100644 --- a/message-translation/README.md +++ b/message-translation/README.md @@ -2,13 +2,13 @@ This template shows how to translate a new message in a given language into multiple destination languages. -## Cloud Function Code +## Functions Code -See file [index.js](index.js) for the code. +See file [index.js](functions/index.js) for the code. This is done by using the Google Translate API to translate the new message. The translated output is written into a fanned out structure using the langauge code as the key. -The dependencies are listed in [package.json](package.json). +The dependencies are listed in [package.json](functions/package.json). ## Sample Database Structure @@ -26,22 +26,20 @@ As an example we'll be using a simple database structure: text: "Hey Mat! How Are you?" ``` -## Trigger rules +When a new message is received we lookup the language message and automatically translate in all other required languages: -Below is the trigger rule for the `translate` function making sure it's triggered when a new message is added. - -``` - "functions": { - ".source": "functions", - "translate": { - "triggers": { - "database": { - "path": "/messages/$languageID/$messageID", - "condition": "newData.child('translated').val() === false" - } - } - } - } ``` - - +/functions-project-12345 + /messages + /en + /key-123456 + translated: true + text: "Hey Bob! How Are you?" + /key-123457 + translated: false + text: "Hey Mat! How Are you?" + /fr + /key-123456 + translated: true + text: "Salut Bob! Comment ca va?" +``` \ No newline at end of file diff --git a/message-translation/functions/index.js b/message-translation/functions/index.js new file mode 100644 index 0000000..95df7a8 --- /dev/null +++ b/message-translation/functions/index.js @@ -0,0 +1,58 @@ +/** + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use strict'; + +const functions = require('firebase-functions'); +var request = require('request-promise'); + +// List of output languages. +var LANGUAGES = ['en', 'es', 'de', 'fr', 'sv', 'ga', 'it', 'jp']; + +// Translate an incoming message. +exports.translate = functions.database().path('/messages/$languageID/$messageID').on('value', event => { + if (event.data.val().translated) { + return; + } + var paths = event.data.ref.toString().split('/'); + var promises = []; + for (var i = 0; i < LANGUAGES.length; i++) { + var language = LANGUAGES[i]; + if (language !== paths[1]) { + promises.push(createTranslationPromise(paths[1], language, event.data)); + } + } + return Promise.all(promises); +}); + +// URL to the Google Translate API. +// TODO: Change `` by your Google Developers Console project API key. +function createTranslateUrl(source, target, payload) { + return `https://www.googleapis.com/language/translate/v2?key=&source=${source}&target=${target}&q=${payload}`; +} + +function createTranslationPromise(source, target, snapshot) { + const key = snapshot.key; + const message = snapshot.val().message; + return request(createTranslateUrl(source, target, message), {resolveWithFullResponse: true}).then( + response => { + if (response.statusCode === 200) { + const data = JSON.parse(response.body).data; + return functions.app.database().ref(`messages/${target}/${key}`) + .set({message: data.translations[0].translatedText, translated: true}); + } + throw response.body; + }); +} diff --git a/message-translation/functions/package.json b/message-translation/functions/package.json new file mode 100644 index 0000000..62bb6c1 --- /dev/null +++ b/message-translation/functions/package.json @@ -0,0 +1,9 @@ +{ + "main": "index.js", + "dependencies": { + "firebase": "^3.3.0", + "firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz", + "request-promise": "^2.0.0", + "rsvp": "^3.1.0" + } +} diff --git a/message-translation/index.js b/message-translation/index.js deleted file mode 100644 index 6f4c4e5..0000000 --- a/message-translation/index.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; - -// Create an all access Firebase Database reference. -var Firebase = require('firebase'); -var env = require('./env'); -var ref = new Firebase(env.get('firebase.database.url'), 'admin'); -ref.auth(env.get('firebase.database.token')); - -var request = require('request-promise'); -var RSVP = require('rsvp'); - -// List of output languages. -var LANGUAGES = ['en', 'es', 'de', 'fr', 'sv', 'ga', 'it', 'jp']; - -// Translate an incoming message. -function translate(context, data) { - var paths = data.path.split("/"); - var promises = []; - ref.child(data.path).once('value').then(function(snap) { - for (var i = 0; i < LANGUAGES.length; i++) { - var language = LANGUAGES[i]; - if (language !== paths[1]) { - promises.push(createTranslationPromise(paths[1], language, snap)); - } - } - RSVP.all(promises).then(function() { - context.done(); - }) - }).catch(context.done); -} - -// URL to the Google Translate API. -// TODO: Change `` by your Google Developers Console project API key. -function createTranslateUrl(source, target, payload) { - return 'https://www.googleapis.com/language/translate/v2?key=&source=' + - source + '&target=' + target + '&q=' + payload; -} - -function createTranslationPromise(source, target, snapshot) { - var key = snapshot.key(); - var message = snapshot.val()['message']; - return request(createTranslateUrl(source, target, message), {resolveWithFullResponse: true}).then( - function(response) { - if (response.statusCode == 200) { - var data = JSON.parse(response.body).data; - return ref.child('messages/' + target + '/' + key) - .set({message: data['translations'][0]['translatedText'], translated: true}); - } else { - throw response.body; - } - }); -} - -module.exports = { - translate: translate -} \ No newline at end of file diff --git a/message-translation/package.json b/message-translation/package.json deleted file mode 100644 index 9367740..0000000 --- a/message-translation/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "main": "index.js", - "dependencies": { - "firebase": "^2.4.0", - "request-promise": "^2.0.0", - "rsvp": "^3.1.0" - } -} diff --git a/minimal-webhook/functions/index.js b/minimal-webhook/functions/index.js index a8b03ee..87a88a5 100644 --- a/minimal-webhook/functions/index.js +++ b/minimal-webhook/functions/index.js @@ -1,5 +1,5 @@ /** - * Copyright 2015 Google Inc. All Rights Reserved. + * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.