Browse Source

Updating remaning samples to 0.5.0

Change-Id: I88fc399339d16fe6d48a6e80dd7f47f576090f5c
ryanpbrewster-patch-1
Nicolas Garnier 8 years ago
parent
commit
34d15ce0a3
  1. 2
      bigquery-import/README.md
  2. 6
      bigquery-import/functions/index.js
  3. 4
      bigquery-import/functions/package.json
  4. 8
      child-count/functions/index.js
  5. 2
      child-count/functions/package.json
  6. 13
      convert-images/functions/index.js
  7. 2
      convert-images/functions/package.json
  8. 6
      delete-unused-accounts-cron/functions/index.js
  9. 2
      email-confirmation/README.md
  10. 12
      email-confirmation/functions/index.js
  11. 2
      email-confirmation/functions/package.json
  12. 17
      exif-images/functions/index.js
  13. 2
      exif-images/functions/package.json
  14. 88
      fcm-notifications/functions/index.js
  15. 5
      fcm-notifications/functions/package.json
  16. 12
      fcm-notifications/functions/service-account.json
  17. 2
      fulltext-search/README.md
  18. 14
      fulltext-search/functions/index.js
  19. 2
      fulltext-search/functions/package.json
  20. 2
      generate-thumbnail/functions/package.json
  21. 5
      instagram-auth/README.md
  22. 8
      instagram-auth/functions/index.js
  23. 3
      instagram-auth/functions/package.json
  24. 6
      lastmodified-tracking/functions/index.js
  25. 2
      lastmodified-tracking/functions/package.json
  26. 2
      limit-children/functions/index.js
  27. 2
      limit-children/functions/package.json
  28. 5
      linkedin-auth/README.md
  29. 8
      linkedin-auth/functions/index.js
  30. 3
      linkedin-auth/functions/package.json
  31. 15
      message-translation/functions/index.js
  32. 2
      message-translation/functions/package.json
  33. 2
      minimal-webhook/functions/index.js
  34. 2
      minimal-webhook/functions/package.json
  35. 3
      moderate-images/functions/index.js
  36. 2
      moderate-images/functions/package.json
  37. 7
      text-moderation/functions/index.js
  38. 2
      text-moderation/functions/package.json
  39. 9
      user-data-cleanup/functions/index.js

2
bigquery-import/README.md

@ -26,5 +26,5 @@ As an example we'll be using a simple logs database structure:
Set the `bigquery.datasetName` and `bigquery.tableName` Google Cloud environment variables to match the Dataset name and the Table name where you want the logs written to. For this use:
```bash
firebase env:set bigquery.datasetName="bar" bigquery.tableName="baz"
firebase functions:config:set bigquery.datasetName="bar" bigquery.tableName="baz"
```

6
bigquery-import/functions/index.js

@ -21,11 +21,11 @@ const bigquery = require('@google-cloud/bigquery');
/**
* Writes all logs from the Realtime Database into bigquery.
*/
exports.addtobigquery = functions.database().path('/logs/$logid').onWrite(event => {
exports.addtobigquery = functions.database.ref('/logs/$logid').onWrite(event => {
// TODO: Make sure you set the `bigquery.datasetName` Google Cloud environment variable.
const dataset = bigquery.dataset(functions.env.bigquery.datasetname);
const dataset = bigquery.dataset(functions.config().bigquery.datasetname);
// TODO: Make sure you set the `bigquery.tableName` Google Cloud environment variable.
const table = dataset.table(functions.env.bigquery.tablename);
const table = dataset.table(functions.config().bigquery.tablename);
return table.insert({
ID: event.data.key,

4
bigquery-import/functions/package.json

@ -3,7 +3,7 @@
"description": "Import data to BigQuery Firebase Functions sample",
"dependencies": {
"@google-cloud/bigquery": "^0.6.0",
"firebase": "^3.6",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
}
}

8
child-count/functions/index.js

@ -15,9 +15,11 @@
*/
'use strict';
var functions = require('firebase-functions');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Keeps track of the length of the 'likes' child list in a separate attribute.
exports.countlikes = functions.database().path('/posts/$postid/likes').onWrite(event => {
return event.adminRef.parent().child('likes_count').set(event.data.numChildren());
exports.countlikes = functions.database.ref('/posts/$postid/likes').onWrite(event => {
return event.data.ref.parent().child('likes_count').set(event.data.numChildren());
});

2
child-count/functions/package.json

@ -2,7 +2,7 @@
"name": "child-count-functions",
"description": "Count Child nodes Firebase Functions sample",
"dependencies": {
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
}
}

13
convert-images/functions/index.js

@ -28,8 +28,9 @@ const JPEG_EXTENSION = 'jpg';
* When an image is uploaded in the Storage bucket it is converted to JPEG automatically using
* ImageMagick.
*/
exports.imageToJPG = functions.storage().onChange(event => {
const filePath = event.data.name;
exports.imageToJPG = functions.storage.object().onChange(event => {
const object = event.data;
const filePath = object.name;
const filePathSplit = filePath.split('/');
const fileName = filePathSplit.pop();
const fileNameSplit = fileName.split('.');
@ -42,19 +43,19 @@ exports.imageToJPG = functions.storage().onChange(event => {
const tempLocalJPEGFile = `${LOCAL_TMP_FOLDER}${JPEGFilePath}`;//
// Exit if this is triggered on a file that is not an image.
if (!event.data.contentType.startsWith('image/')) {
if (!object.contentType.startsWith('image/')) {
console.log('This is not an image.');
return;
}
// Exit if the image is already a JPEG.
if (event.data.contentType.startsWith('image/jpeg')) {
if (object.contentType.startsWith('image/jpeg')) {
console.log('Already a JPEG.');
return;
}
// Exit if this is a move or deletion event.
if (event.data.resourceState === 'not_exists') {
if (object.resourceState === 'not_exists') {
console.log('This is a deletion event.');
return;
}
@ -62,7 +63,7 @@ exports.imageToJPG = functions.storage().onChange(event => {
// Create the temp directory where the storage file will be downloaded.
return mkdirp(tempLocalDir).then(() => {
// Download file from bucket.
const bucket = gcs.bucket(event.data.bucket);
const bucket = gcs.bucket(object.bucket);
return bucket.file(filePath).download({
destination: tempLocalFile
}).then(() => {

2
convert-images/functions/package.json

@ -4,7 +4,7 @@
"dependencies": {
"@google-cloud/storage": "^0.4.0",
"child-process-promise": "^2.2.0",
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"mkdirp": "^0.5.1",
"mkdirp-promise": "^4.0.0"

6
delete-unused-accounts-cron/functions/index.js

@ -29,7 +29,7 @@ const MAX_CONCURRENT = 3;
* The request needs to be authorized by passing a 'key' query parameter in the URL. This key must
* match a key set as an environment variable using `firebase functions:config:set cron.key="YOUR_KEY"`.
*/
exports.accountcleanup = functions.https().onRequest((req, res) => {
exports.accountcleanup = functions.https.onRequest((req, res) => {
const key = req.query.key;
// Exit if the keys don't match
@ -88,9 +88,9 @@ function getUsers(userIds = [], nextPageToken, accessToken) {
return userIds;
}
if (resp.nextPageToken) {
return getUsers(resp.users, resp.nextPageToken, accessToken);
return getUsers(userIds.concat(resp.users), resp.nextPageToken, accessToken);
}
return resp.users;
return userIds.concat(resp.users);
});
});
}

2
email-confirmation/README.md

@ -37,7 +37,7 @@ The function triggers on changes to `/users/$uid` and exits if there are no chan
Set the `gmail.email` and `gmail.password` Google Cloud environment variables to match the email and password of the Gmail account used to send emails. For this use:
```bash
firebase env:set gmail.email="myusername@gmail.com" gmail.password="secretpassword"
firebase functions:config:set gmail.email="myusername@gmail.com" gmail.password="secretpassword"
```
This sample comes with a web-based UI for testing the function. To set it up:

12
email-confirmation/functions/index.js

@ -19,18 +19,20 @@ const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
// Sends an email confirmation when a user changes his mailing list subscription.
exports.sendEmailConfirmation = functions.database().path('/users/{uid}').onWrite(event => {
exports.sendEmailConfirmation = functions.database.ref('/users/{uid}').onWrite(event => {
// Configure the email transport using the default SMTP transport and a GMail account.
// See: https://nodemailer.com/
// For other types of transports (Amazon SES, Sendgrid...) see https://nodemailer.com/2-0-0-beta/setup-transporter/
// TODO: Make sure you configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(
`smtps://${encodeURIComponent(functions.env.gmail.email)}:${encodeURIComponent(functions.env.gmail.password)}@smtp.gmail.com`);
`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);
const data = event.data;
const val = data.val();
const snapshot = event.data;
const val = snapshot.val();
if (!data.changed('subscribedToMailingList')) {
if (!snapshot.changed('subscribedToMailingList')) {
return;
}

2
email-confirmation/functions/package.json

@ -3,7 +3,7 @@
"description": "Send Email confirmation upon sign up to a Mailing list Firebase Functions sample",
"dependencies": {
"nodemailer": "^2.4.1",
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
}
}

17
exif-images/functions/index.js

@ -16,6 +16,8 @@
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const gcs = require('@google-cloud/storage')();
const exec = require('child-process-promise').exec;
const LOCAL_TMP_FOLDER = '/tmp/';
@ -24,27 +26,26 @@ const LOCAL_TMP_FOLDER = '/tmp/';
* When an image is uploaded in the Storage bucket the information and metadata of the image (the
* output of ImageMagick's `identify -verbose`) is saved in the Realtime Database.
*/
exports.metadata = functions.storage().onChange(event => {
console.log(event);
const filePath = event.data.name;
exports.metadata = functions.storage.object().onChange(event => {
const object = event.data;
const filePath = object.name;
const fileName = filePath.split('/').pop();
const tempLocalFile = `${LOCAL_TMP_FOLDER}${fileName}`;
// Exit if this is triggered on a file that is not an image.
if (!event.data.contentType.startsWith('image/')) {
if (!object.contentType.startsWith('image/')) {
console.log('This is not an image.');
return;
}
// Exit if this is a move or deletion event.
if (event.data.resourceState === 'not_exists') {
if (object.resourceState === 'not_exists') {
console.log('This is a deletion event.');
return;
}
// Download file from bucket.
const bucket = gcs.bucket(event.data.bucket);
const bucket = gcs.bucket(object.bucket);
return bucket.file(filePath).download({
destination: tempLocalFile
}).then(() => {
@ -52,7 +53,7 @@ exports.metadata = functions.storage().onChange(event => {
return exec(`identify -verbose "${tempLocalFile}"`).then(result => {
const metadata = imageMagickOutputToObject(result.stdout);
// Save metadata to realtime datastore.
return functions.app.database().ref(makeKeyFirebaseCompatible(filePath)).set(metadata).then(() => {
return admin.database().ref(makeKeyFirebaseCompatible(filePath)).set(metadata).then(() => {
console.log('Wrote to:', filePath, 'data:', metadata);
});
});

2
exif-images/functions/package.json

@ -4,7 +4,7 @@
"dependencies": {
"@google-cloud/storage": "^0.4.0",
"child-process-promise": "^2.2.0",
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
}
}

88
fcm-notifications/functions/index.js

@ -16,21 +16,16 @@
'use strict';
const functions = require('firebase-functions');
const firebaseAdmin = require('firebase-admin');
const serviceAccount = require('./service-account.json');
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount),
databaseURL: `https://${serviceAccount.project_id}.firebaseio.com`
});
const rp = require('request-promise-native');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/**
* Triggers when a user gets a new follower and sends a notification.
*
* Followers add a flag to `followers/{followedUid}/{followerUid}`.
* Users save their device notification tokens to `users/{followedUid}/notificationTokens/{notificationToken}`.
* Followers add a flag to `/followers/{followedUid}/{followerUid}`.
* Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`.
*/
exports.sendFollowerNotification = functions.database().path('followers/{followedUid}/{followerUid}').onWrite(event => {
exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => {
const followerUid = event.params.followerUid;
const followedUid = event.params.followedUid;
// If un-follow we exit the function.
@ -40,10 +35,10 @@ exports.sendFollowerNotification = functions.database().path('followers/{followe
console.log('We have a new follower UID:', followerUid, 'for user:', followerUid);
// Get the list of device notification tokens.
const getNotificationTokensPromise = firebaseAdmin.database().ref(`users/${followedUid}/notificationTokens`).once('value');
const getNotificationTokensPromise = admin.database().ref(`/users/${followedUid}/notificationTokens`).once('value');
// Get the follower profile.
const getFollowerProfilePromise = firebaseAdmin.auth().getUser(followerUid);
const getFollowerProfilePromise = admin.auth().getUser(followerUid);
return Promise.all([getNotificationTokensPromise, getFollowerProfilePromise]).then(results => {
const tokensSnapshot = results[0];
@ -55,56 +50,33 @@ exports.sendFollowerNotification = functions.database().path('followers/{followe
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
console.log('Fetched follower profile', follower);
const displayName = follower.displayName;
const profilePic = follower.photoURL;
// Sends notifications to all tokens.
const notificationPromises = [];
tokensSnapshot.forEach(tokenSnapshot => {
const token = tokenSnapshot.key;
const notificationPromise = sendNotification(displayName, token, followedUid, profilePic);
notificationPromises.push(notificationPromise);
});
return Promise.all(notificationPromises).then(() => {
console.log('Marked notification as sent.');
console.log('Finished sending notifications.');
});
});
});
/**
* Sends a "New follower" notification to the given `token`.
* Removes/cleans up the token from the database if they are not registered anymore.
*/
function sendNotification(displayName, token, followedUid, profilePic) {
// Prepare the REST request to the Firebase Cloud Messaging API.
var options = {
method: 'POST',
uri: 'https://fcm.googleapis.com/fcm/send',
headers: {
Authorization: `key=${functions.env.firebase.apiKey}`
},
body: {
// Notification details.
const payload = {
notification: {
title: 'You have a new follower!',
body: `${displayName} is now following you.`,
icon: profilePic || 'https://ssl.gstatic.com/images/icons/material/product/1x/avatar_square_blue_120dp.png'
},
to: token
},
json: true
};
body: `${follower.displayName} is now following you.`,
icon: follower.photoURL
}
};
// Send the REST request to the Firebase Cloud Messaging API.
return rp(options).then(resp => {
console.log('Sent a notification.', resp.success ? 'Success' : 'Failure');
// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());
// Cleanup the tokens who are not registered anymore.
if (resp.failure && resp.results[0].error === 'NotRegistered') {
return firebaseAdmin.database().ref(`users/${followedUid}/notificationTokens/${token}`).remove().then(() => {
console.log('Removed unregistered token.');
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
// For each message check if there was an error.
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
// Cleanup the tokens who are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
return tokensSnapshot.ref.child(tokens[index]).remove();
}
}
});
}
});
});
}
});

5
fcm-notifications/functions/package.json

@ -2,10 +2,7 @@
"name": "fcm-notifications-functions",
"description": "Send FCM notifications Firebase Functions sample",
"dependencies": {
"firebase": "^3.6",
"firebase-admin": "^4.0.1",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"request": "^2.78.0",
"request-promise-native": "^1.0.3"
}
}

12
fcm-notifications/functions/service-account.json

@ -1,12 +0,0 @@
{
"type": "service_account",
"project_id": "functions-fcm",
"private_key_id": "f49aa12fc8ce9ddc7c5a5f2e56bfb34a4b1376cd",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQCe42jBELgCnq\n94iq74kLeyzwLGEsbfdVang7F5Lf76+BIhQ7LziVRmMNJcvwRz/UptGRc58v0xFz\n55a9hCRuRFN04glUOPS+lNzNtJN9cGSsZZV+36h6/nvEnnuJxHGXZtmTD8ymeaJs\nqL0RxAa6RSwNkweYV0mgCILqX9+qcrU494n3grWVgWop4HrV+IWzvZ9QMHb9K4w1\nwQoAFpiwD0B45abgPT68UbFWcy8wYoQgXwrvKc3n2z4RevfTi5EUmd76fd52PKBc\nAbLa/NcHB9iQ0+rR/u9zLAZ3Rm/1Wso+99hBCFMLHZHa+ujFI+q4Y+Fyw2SLgVgF\ni9iBCFvTAgMBAAECggEBAKCJmT6Ula6nRzGftOIbmEi407O+u3n6netXDtKi3V9b\nabaforcNOH/Q4izKJvcTNEmYNY4liAjyurwTUXqLl0VUCobeys4oaY0L+NvwZgRd\nkAKNHXDbjPrkmIPgvHpSkkmAP5PBlG4+3L029TfZakuhh14uQKUpbpJFHylXtJSl\nLVzWqVD0d3P1Z5KqHau8FLOtq+TwlL9tQjh1Ym6wqvdqMi4NHkdMCVIWtXyfI8xw\nGKaPlLMx1hYsRbbcnnxzzauZrgEOyT/q4Q1Hn7eENl1j0SVyTe01tJA2Odw8NkIu\npmyeMIztc/WqsOml+zGwgajw/EjJ6TabZnj13Bii9JkCgYEA8rvtG6wIGOZlQ3hJ\nbwip9LFIMZZiI0EDytnansAOVujIE7/UY2/wfyE4aOZgHBOWzbbUkZ2S4vQ0DPeg\nmQ6As1Kqo4g8zdXZjqgqVj4I83WNPFHTCrSXaK47p4YtCcHBy2M3Pu6t/1vQ5fMP\nFlo57M8Ex5MNDMGE21F4tAusNNUCgYEA22iVyqxLsL4W0CidOZ+1snxaxjtKDHt9\nBCSrs06itcnnhTSLBI55BHqI6stb+GHbZOaZ6/lSJjPKr+IFy5T1BzfgiMEcY6ee\nsxU+5lQxJ6D1JKkLdUtNppRKCyx0q2G7qscD7CpmBpXCKt/FnBqpqtjfBsqT1dhZ\nXoG/LczkQgcCgYASOAbA9/WXoNti6Ali+xx+kDvh9O6ixMN7G0Tse2/YGBrEWLah\nTAqaEC1Cul/mW5YLFLj5wQEAZeHuQzvboRoJ25+RLK2bqXxt17Nty7QySdVy/JVB\njXJ72fACT/DbdZ6NHIJOB+4pZ4PTbp3oSJdmbddm/2OQXIoTSBcuNF4VjQKBgFt+\nXGB8wr98NUUueonqCLnaU3wwgyt7X2GX7SXDl+RYwrvwcjw/MUXl1yyaCssj+3oz\nE2KswE3/8PixNxtzDU6qRW6hoLYJ0wr4xBcGas0MuM1F1OpfsYzSb6IDMs+43KpV\nfVRBRfRfBO4eDGiRUclV0IMjfMyDAJmBX3i45UKHAoGBAMyKh8ysZuZypcwuWXHn\ncUEv3YjciGzfhShVCyCLJ21IEr/Fpt4DwIO8lyaL1s1ez0q39QnTc/ZeHG6Q6trZ\nCpT+zExvENE2tRQFR/M4eEwsZM+dOYkywoM4SDmEzck+Nt9FtlkL+tR1DB+vT0/x\ns67Nlpbyq0AbxtptOSW7HWMp\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-oz89s@functions-fcm.iam.gserviceaccount.com",
"client_id": "115601641616008366344",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-oz89s%40functions-fcm.iam.gserviceaccount.com"
}

2
fulltext-search/README.md

@ -45,5 +45,5 @@ Create an Algolia account at [www.algolia.com](https://www.algolia.com/)
Set the `algolia.key` and `algolia.password` Google Cloud environment variables to match the Algolia Key and Secret of your account. For this use:
```bash
firebase env:set algolia.key="mykey" algolia.secret="secret"
firebase functions:config:set algolia.key="mykey" algolia.secret="secret"
```

14
fulltext-search/functions/index.js

@ -16,28 +16,30 @@
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Authenticate to Algolia Database.
const algoliasearch = require('algoliasearch');
// Updates the search index when new blog entries are created or updated.
exports.indexentry = functions.database().path('/blog-posts/$blogid').onWrite(event => {
exports.indexentry = functions.database.ref('/blog-posts/$blogid').onWrite(event => {
// TODO: Make sure you configure the `algolia.key` and `algolia.secret` Google Cloud environment variables.
const client = algoliasearch(functions.env.algolia.key, functions.env.algolia.secret);
const client = algoliasearch(functions.config().algolia.key, functions.config().algolia.secret);
const index = client.initIndex('users');
const firebaseObject = event.data.val();
firebaseObject.objectID = event.data.key;
return index.saveObject(firebaseObject).then(
() => functions.app.database().ref(event.timestamp));
() => admin.database().ref(event.timestamp));
});
// Starts a search query whenever a query is requested (by adding one to the `/search/queries`
// element. Search results are then written under `/search/results`.
exports.searchentry = functions.database().path('/search/queries/$queryid').onWrite(event => {
exports.searchentry = functions.database.ref('/search/queries/$queryid').onWrite(event => {
// TODO: Make sure you configure the `algolia.key` and `algolia.secret` Google Cloud environment variables.
const client = algoliasearch(functions.env.algolia.key, functions.env.algolia.secret);
const client = algoliasearch(functions.config().algolia.key, functions.config().algolia.secret);
const index = client.initIndex('users');
const query = event.data.val().query;
@ -48,6 +50,6 @@ exports.searchentry = functions.database().path('/search/queries/$queryid').onWr
'/last_query': event.timestamp
};
updates[`/search/results/${key}`] = content;
return functions.app.database().ref().update(updates);
return admin.database().ref().update(updates);
});
});

2
fulltext-search/functions/package.json

@ -2,7 +2,7 @@
"name": "fulltext-search-functions",
"description": "Full Text Search with Algolia Firebase Functions sample",
"dependencies": {
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"algoliasearch": "^3.10.2"
}

2
generate-thumbnail/functions/package.json

@ -4,7 +4,7 @@
"dependencies": {
"@google-cloud/storage": "^0.4.0",
"child-process-promise": "^2.2.0",
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"mkdirp": "^0.5.1",
"mkdirp-promise": "^4.0.0"

5
instagram-auth/README.md

@ -10,18 +10,17 @@ Create and setup the Firebase project:
1. Enable Billing on your Firebase the project by switching to the **Blaze** plan, this is currently needed to be able to perform HTTP requests to external services from a Cloud Function.
1. Copy the Web initialisation snippet from **Firebase Console > Overview > Add Firebase to your web app** and paste it in `public/index.html` and `public/popup.html` in lieu of the placeholders (where the `TODO(DEVELOPER)` are located).
Create and provide a Service Account's keys:
Create and provide a Service Account's credentials:
1. Create a Service Accounts file as described in the [Server SDK setup instructions](https://firebase.google.com/docs/server/setup#add_firebase_to_your_app).
1. Save the Service Account credential file as `./functions/service-account.json`
Create and setup your Instagram app:
1. Register an Instagram app on [Instagram for Developers](https://www.instagram.com/developer/). You'll need to **Register a New Client**.
1. Once Your app is created make sure you specify your app's callback URL in the list of **Valid redirect URIs** of your Instagram app. You should whitelist `https://localhost:5000/popup.html` for local development and if you deploy on App Engine (See Deploy section below) you should whitelist the URL `https://<application-id>.firebaseapp.com/popup.html`.
1. Copy the **Client ID** and **Client Secret** of your Instagram app and use them to set the `instagram.clientId` and `instagram.clientSecret` Google Cloud environment variables. For this use:
```bash
firebase env:set instagram.clientId="yourClientID" instagram.clientSecret="yourClientSecret"
firebase functions:config:set instagram.clientId="yourClientID" instagram.clientSecret="yourClientSecret"
```
> Make sure the Instagram Client Secret is always kept secret. For instance do not save it in your version control system.

8
instagram-auth/functions/index.js

@ -38,8 +38,8 @@ function instagramOAuth2Client() {
// TODO: Configure the `instagram.clientId` and `instagram.clientSecret` Google Cloud environment variables.
const credentials = {
client: {
id: functions.env.instagram.clientId,
secret: functions.env.instagram.clientSecret
id: functions.config().instagram.clientId,
secret: functions.config().instagram.clientSecret
},
auth: {
tokenHost: 'https://api.instagram.com',
@ -53,7 +53,7 @@ function instagramOAuth2Client() {
* Redirects the User to the Instagram authentication consent screen. Also the 'state' cookie is set for later state
* verification.
*/
exports.redirect = functions.https().onRequest((req, res) => {
exports.redirect = functions.https.onRequest((req, res) => {
const oauth2 = instagramOAuth2Client();
cookieParser()(req, res, () => {
@ -76,7 +76,7 @@ exports.redirect = functions.https().onRequest((req, res) => {
* The Firebase custom auth token, display name, photo URL and Instagram acces token are sent back in a JSONP callback
* function with function name defined by the 'callback' query parameter.
*/
exports.token = functions.https().onRequest((req, res) => {
exports.token = functions.https.onRequest((req, res) => {
const oauth2 = instagramOAuth2Client();
try {

3
instagram-auth/functions/package.json

@ -4,8 +4,7 @@
"dependencies": {
"cookie-parser": "^1.4.3",
"crypto": "0.0.3",
"firebase-admin": "^4.0",
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"request": "^2.74.0",
"request-promise-native": "^1.0.3",

6
lastmodified-tracking/functions/index.js

@ -16,9 +16,11 @@
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/**
* This Function updates the `/lastmodified` with the timestamp of the last write to `/chat/$message`.
*/
exports.touch = functions.database().path('/chat/$message').onWrite(
event => functions.app.database().ref('/lastmodified').set(event.timestamp));
exports.touch = functions.database.ref('/chat/$message').onWrite(
event => admin.database().ref('/lastmodified').set(event.timestamp));

2
lastmodified-tracking/functions/package.json

@ -2,7 +2,7 @@
"name": "lastmodified-tracking-functions",
"description": "Track Lastmodified date of nodes Firebase Functions sample",
"dependencies": {
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
}
}

2
limit-children/functions/index.js

@ -22,7 +22,7 @@ const MAX_LOG_COUNT = 5;
// Removes siblings of the node that element that triggered the function if there are more than MAX_LOG_COUNT.
// In this example we'll keep the max number of chat message history to MAX_LOG_COUNT.
exports.truncate = functions.database().path('/chat/$messageid').onWrite(event => {
exports.truncate = functions.database.ref('/chat/$messageid').onWrite(event => {
const parentRef = event.data.ref.parent();
return parentRef.once('value').then(snapshot => {
if (snapshot.numChildren() > MAX_LOG_COUNT) {

2
limit-children/functions/package.json

@ -2,7 +2,7 @@
"name": "limit-children-functions",
"description": "Limit number of child nodes Firebase Functions sample",
"dependencies": {
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
}
}

5
linkedin-auth/README.md

@ -10,11 +10,10 @@ Create and setup the Firebase project:
1. Enable Billing on your Firebase the project by switching to the **Blaze** plan, this is currently needed to be able to perform HTTP requests to external services from a Cloud Function.
1. Copy the Web initialisation snippet from **Firebase Console > Overview > Add Firebase to your web app** and paste it in `public/index.html` and `public/popup.html` in lieu of the placeholders (where the `TODO(DEVELOPER)` are located).
Create and provide a Service Account's keys:
Create and provide a Service Account's credentials:
1. Create a Service Accounts file as described in the [Server SDK setup instructions](https://firebase.google.com/docs/server/setup#add_firebase_to_your_app).
1. Save the Service Account credential file as `./functions/service-account.json`
Create and setup your LinkedIn app:
1. Create a LinkedIn app in the [LinkedIn Developers website](https://www.linkedin.com/developer/apps/).
1. Add the URL `https://<application-id>.firebaseapp.com/popup.html` to the
@ -22,7 +21,7 @@ Create and setup your LinkedIn app:
1. Copy the **Client ID** and **Client Secret** of your LinkedIn app and use them to set the `linkedIn.clientId` and `linkedIn.clientSecret` Google Cloud environment variables. For this use:
```bash
firebase env:set linkedIn.clientId="yourClientID" linkedIn.clientSecret="yourClientSecret"
firebase functions:config:set linkedIn.clientId="yourClientID" linkedIn.clientSecret="yourClientSecret"
```
> Make sure the LinkedIn Client Secret is always kept secret. For instance do not save this in your version control system.

8
linkedin-auth/functions/index.js

@ -36,8 +36,8 @@ function linkedInClient() {
// Instagram OAuth 2 setup
// TODO: Configure the `linkedIn.clientId` and `linkedIn.clientSecret` Google Cloud environment variables.
return require('node-linkedin')(
functions.env.linkedIn.clientId,
functions.env.linkedIn.clientSecret,
functions.config().linkedIn.clientId,
functions.config().linkedIn.clientSecret,
`https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`);
}
@ -45,7 +45,7 @@ function linkedInClient() {
* Redirects the User to the LinkedIn authentication consent screen. ALso the 'state' cookie is set for later state
* verification.
*/
exports.redirect = functions.https().onRequest((req, res) => {
exports.redirect = functions.https.onRequest((req, res) => {
const Linkedin = linkedInClient();
cookieParser()(req, res, () => {
@ -62,7 +62,7 @@ exports.redirect = functions.https().onRequest((req, res) => {
* The Firebase custom auth token is sent back in a JSONP callback function with function name defined by the
* 'callback' query parameter.
*/
exports.token = functions.https().onRequest((req, res) => {
exports.token = functions.https.onRequest((req, res) => {
const Linkedin = linkedInClient();
try {

3
linkedin-auth/functions/package.json

@ -4,8 +4,7 @@
"dependencies": {
"cookie-parser": "^1.4.3",
"crypto": "0.0.3",
"firebase-admin": "^4.0",
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"node-linkedin": "^0.5.4"
}

15
message-translation/functions/index.js

@ -16,22 +16,25 @@
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const request = require('request-promise');
// List of output languages.
const LANGUAGES = ['en', 'es', 'de', 'fr', 'sv', 'ga', 'it', 'jp'];
// Translate an incoming message.
exports.translate = functions.database().path('/messages/$languageID/$messageID').onWrite(event => {
if (event.data.val().translated) {
exports.translate = functions.database.ref('/messages/$languageID/$messageID').onWrite(event => {
const snapshot = event.data;
if (snapshot.val().translated) {
return;
}
const paths = event.data.ref.toString().split('/');
const paths = snapshot.ref.toString().split('/');
const promises = [];
for (let i = 0; i < LANGUAGES.length; i++) {
var language = LANGUAGES[i];
if (language !== paths[1]) {
promises.push(createTranslationPromise(paths[1], language, event.data));
promises.push(createTranslationPromise(paths[1], language, snapshot));
}
}
return Promise.all(promises);
@ -39,7 +42,7 @@ exports.translate = functions.database().path('/messages/$languageID/$messageID'
// URL to the Google Translate API.
function createTranslateUrl(source, target, payload) {
return `https://www.googleapis.com/language/translate/v2?key=${functions.env.firebase.apiKey}&source=${source}&target=${target}&q=${payload}`;
return `https://www.googleapis.com/language/translate/v2?key=${functions.config().firebase.apiKey}&source=${source}&target=${target}&q=${payload}`;
}
function createTranslationPromise(source, target, snapshot) {
@ -49,7 +52,7 @@ function createTranslationPromise(source, target, snapshot) {
response => {
if (response.statusCode === 200) {
const data = JSON.parse(response.body).data;
return functions.app.database().ref(`messages/${target}/${key}`)
return admin.database().ref(`/messages/${target}/${key}`)
.set({message: data.translations[0].translatedText, translated: true});
}
throw response.body;

2
message-translation/functions/package.json

@ -2,7 +2,7 @@
"name": "message-translation-functions",
"description": "Transalte Messages Firebase Functions sample",
"dependencies": {
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"request-promise": "^2.0.0"
}

2
minimal-webhook/functions/index.js

@ -25,7 +25,7 @@ const WEBHOOK_URL = 'http://requestb.in/1mqw97l1';
// Reads the content of the node that triggered the function and sends it to the registered Webhook
// URL.
exports.webhook = functions.database().path('/hooks/$hookId').onWrite(event => {
exports.webhook = functions.database.ref('/hooks/$hookId').onWrite(event => {
return request({
uri: WEBHOOK_URL,
method: 'POST',

2
minimal-webhook/functions/package.json

@ -2,7 +2,7 @@
"name": "minimal-webhook-functions",
"description": "Queries a Webhook Firebase Functions sample",
"dependencies": {
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"request-promise": "^2.0.0"
}

3
moderate-images/functions/index.js

@ -26,7 +26,8 @@ const LOCAL_TMP_FOLDER = '/tmp/';
* When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision
* API and if it is we blur it using ImageMagick.
*/
exports.blurOffensiveImages = functions.storage().onChange(object => {
exports.blurOffensiveImages = functions.storage.object().onChange(event => {
const object = event.data;
const file = gcs.bucket(object.bucket).file(object.name);
// Exit if this is a move or deletion event.

2
moderate-images/functions/package.json

@ -5,7 +5,7 @@
"@google-cloud/storage": "^0.4.0",
"@google-cloud/vision": "^0.5.0",
"child-process-promise": "^2.2.0",
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"mkdirp": "^0.5.1",
"mkdirp-promise": "^4.0.0"

7
text-moderation/functions/index.js

@ -17,11 +17,12 @@
const functions = require('firebase-functions');
const capitalizeSentence = require('capitalize-sentence');
const badWordsFilter = require('bad-words')();
const Filter = require('bad-words');
const badWordsFilter = new Filter();
// Moderates messages by lowering all uppercase messages and removing swearwords.
exports.moderator = functions.database()
.path('/messages/{messageId}').onWrite(event => {
exports.moderator = functions.database
.ref('/messages/{messageId}').onWrite(event => {
const message = event.data.val();
if (message && !message.sanitized) {

2
text-moderation/functions/package.json

@ -4,7 +4,7 @@
"dependencies": {
"bad-words": "^1.3.1",
"capitalize-sentence": "^0.1.2",
"firebase": "^3.6",
"firebase-admin": "^4.1.1",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz"
}
}

9
user-data-cleanup/functions/index.js

@ -16,10 +16,11 @@
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Deletes the user data in the Realtime Datastore when he deletes his account.
exports.cleanupUserData = functions.auth().onDelete(event => {
// Deletes the user data in the Realtime Datastore when the accounts are deleted.
exports.cleanupUserData = functions.auth.user().onDelete(event => {
const uid = event.data.uid;
return functions.app.database().ref(`/users/${uid}`).remove();
return admin.database().ref(`/users/${uid}`).remove();
});

Loading…
Cancel
Save