Cloud Messaging と Cloud Functions を使用して Web アプリの通知を送信する

1。概要

この Codelab では、Cloud Functions for Firebase を使用してチャット ウェブアプリに機能を追加し、チャット アプリのユーザーに通知を送信する方法を学習します。

3b1284f5144b54f6.png

学習内容

  • Firebase SDK を使用して Google Cloud Functions を作成します。
  • Auth、Cloud Storage、Cloud Firestore イベントに基づいて Cloud Functions をトリガーします。
  • Web アプリに Firebase Cloud Messaging のサポートを追加します。

必要なもの

  • クレジットカード。 Cloud Functions for Firebase には Firebase Blaze プランが必要です。つまり、クレジット カードを使用して Firebase プロジェクトで課金を有効にする必要があります。
  • WebStormAtomSublimeなど、任意の IDE/テキスト エディター。
  • NodeJS v9 がインストールされたシェル コマンドを実行するためのターミナル。
  • Chrome などのブラウザ。
  • サンプルコード。これについては、次のステップを参照してください。

2. サンプルコードを入手する

コマンド ラインからGitHub リポジトリのクローンを作成します。

git clone https://github.com/firebase/friendlychat

スターター アプリをインポートする

IDE を使用して、 android_studio_folder.pngサンプル コード ディレクトリのcloud-functions-startディレクトリ。このディレクトリには、完全に機能する Chat Web App で構成される Codelab の開始コードが含まれています。

3. Firebase プロジェクトを作成し、アプリをセットアップする

プロジェクトを作成

Firebase Consoleで、 [プロジェクトの追加]をクリックして、 FriendlyChatという名前を付けます。

[プロジェクトの作成]をクリックします。

Blaze プランにアップグレードする

Cloud Functions for Firebase を使用するには、Firebase プロジェクトをBlaze 料金プランにアップグレードする必要があります。これには、クレジット カードまたは別の請求方法を Google Cloud アカウントに追加する必要があります。

Blaze プランのプロジェクトを含むすべての Firebase プロジェクトは、引き続き Cloud Functions の無料使用割り当てにアクセスできます。この Codelab で概説されている手順は、無料利用枠の使用制限内に収まります。ただし、Cloud Functions ビルド イメージをホストするために使用される Cloud Storage から少額の料金 (約 $0.03 ) が発生します。

クレジット カードにアクセスできない場合、または Blaze プランを使い続けることに抵抗がある場合は、ローカル マシンで Cloud Functions を無料でエミュレートできるFirebase Emulator Suiteの使用を検討してください。

Google 認証を有効にする

ユーザーがアプリにサインインできるようにするには、有効にする必要がある Google 認証を使用します。

Firebase コンソールで、 [ビルド] セクション > [認証] > [サインイン方法]タブを開きます (または、ここをクリックしてそこに移動します)。次に、 Googleログイン プロバイダを有効にして[保存]をクリックします。これにより、ユーザーは Google アカウントを使用して Web アプリにサインインできるようになります。

また、アプリの公開名をFriendly Chatに自由に設定してください。

8290061806aacb46.png

クラウド ストレージを有効にする

アプリは Cloud Storage を使用して写真をアップロードします。 Firebase プロジェクトで Cloud Storage を有効にするには、 [ストレージ]セクションにアクセスして[開始]ボタンをクリックします。そこの手順を実行すると、Cloud Storage の場所に使用するデフォルト値が表示されます。その後、 [完了]をクリックします。

ウェブアプリを追加する

Firebase コンソールで、ウェブアプリを追加します。これを行うには、 [Project Settings]に移動し、 [Add app]まで下にスクロールします。プラットフォームとして Web を選択し、Firebase Hosting をセットアップするためのボックスをオンにしてから、アプリを登録し、 [次へ]をクリックして残りの手順を実行し、最後に[Continue to console]をクリックします。

4. Firebase コマンドライン インターフェースをインストールする

Firebase コマンド ライン インターフェース (CLI) を使用すると、Web アプリをローカルで提供し、Web アプリと Cloud Functions をデプロイできます。

CLI をインストールまたはアップグレードするには、次の npm コマンドを実行します。

npm -g install firebase-tools

CLI が正しくインストールされたことを確認するには、コンソールを開いて次を実行します。

firebase --version

Cloud Functions に必要な最新機能がすべて含まれるように、Firebase CLI のバージョンが4.0.0以上であることを確認してください。そうでない場合は、上記のようにnpm install -g firebase-toolsを実行してアップグレードします。

次を実行して、Firebase CLI を承認します。

firebase login

cloud-functions-startディレクトリにいることを確認してから、Firebase プロジェクトを使用するように Firebase CLI を設定します。

firebase use --add

次に、プロジェクト ID を選択し、指示に従います。プロンプトが表示されたら、 codelabなどの任意のエイリアスを選択できます。

5. Web アプリをデプロイして実行する

プロジェクトをインポートして構成したので、初めて Web アプリを実行する準備が整いました。ターミナル ウィンドウを開き、 cloud-functions-startフォルダーに移動し、次を使用して Web アプリを Firebase ホスティングにデプロイします。

firebase deploy --except functions

これは、表示されるコンソール出力です。

i deploying database, storage, hosting
✔  database: rules ready to deploy.
i  storage: checking rules for compilation errors...
✔  storage: rules file compiled successfully
i  hosting: preparing ./ directory for upload...
✔  hosting: ./ folder uploaded successfully
✔ storage: rules file compiled successfully
✔ hosting: 8 files uploaded successfully
i starting release process (may take several minutes)...

✔ Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview
Hosting URL: https://friendlychat-1234.firebaseapp.com

ウェブアプリを開く

最後の行には、ホスティング URL が表示されます。 Web アプリは、https://<project-id>.firebaseapp.com の形式であるこの URL から提供されるようになりました。それを開く。チャット アプリの機能する UI が表示されます。

[SIGN-IN WITH GOOGLE]ボタンを使用してアプリにサインインし、自由にメッセージを追加して画像を投稿してください。

3b1284f5144b54f6.png

新しいブラウザで初めてアプリにサインインする場合は、プロンプトが表示されたら通知を許可してください。 8b9d0c66dc36153d.png

後で通知を有効にする必要があります。

誤って[ブロック]をクリックしてしまった場合は、Chrome オムニバーの URL の左側にある🔒 安全なボタンをクリックし、 [通知]の横にあるバーを切り替えて、この設定を変更できます。

e926868b0546ed71.png

ここで、Firebase SDK for Cloud Functions を使用していくつかの機能を追加します。

6. 関数ディレクトリ

Cloud Functions を使用すると、サーバーをセットアップしなくても、クラウドで実行されるコードを簡単に作成できます。 Firebase Auth、Cloud Storage、および Firebase Firestore データベース イベントに反応する関数を作成する方法について説明します。 Authから始めましょう。

Firebase SDK for Cloud Functions を使用する場合、Functions コードはfunctionsディレクトリの下にあります (デフォルト)。 Functions コードもNode.jsアプリであるため、アプリに関する情報を提供し、依存関係を一覧表示するpackage.json必要です。

簡単にするために、コードを配置するfunctions/index.jsファイルを既に作成しています。先に進む前に、このファイルを自由に調べてください。

cd functions
ls

Node.jsに慣れていない場合は、Codelab を続行する前に、Node.js について詳しく学んでおくと役立ちます。

package.jsonファイルには、 Cloud Functions 用の Firebase SDKFirebase Admin SDK の2 つの必要な依存関係が既にリストされています。それらをローカルにインストールするには、 functionsフォルダーに移動して次を実行します。

npm install

index.jsファイルを見てみましょう。

index.js

/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * ...
 */

// TODO(DEVELOPER): Import the Cloud Functions for Firebase and the Firebase Admin modules here.

// TODO(DEVELOPER): Write the addWelcomeMessage Function here.

// TODO(DEVELOPER): Write the blurImages Function here.

// TODO(DEVELOPER): Write the sendNotification Function here.

必要なモジュールをインポートし、TODO の代わりに 3 つの関数を記述します。必要な Node モジュールのインポートから始めましょう。

7. Cloud Functions と Firebase Admin モジュールをインポートする

この Codelab では 2 つのモジュールが必要になりますfirebase-functions使用すると、Cloud Functions のトリガーとログを書き込むことができますfirebase-adminを使用すると、管理者アクセス権を持つサーバーで Firebase プラットフォームを使用して、Cloud Firestore への書き込みや FCM 通知の送信などのアクションを実行できます。

index.jsファイルで、最初のTODO次のように置き換えます。

index.js

/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * ...
 */

// Import the Firebase SDK for Google Cloud Functions.
const functions = require('firebase-functions');
// Import and initialize the Firebase Admin SDK.
const admin = require('firebase-admin');
admin.initializeApp();

// TODO(DEVELOPER): Write the addWelcomeMessage Function here.

// TODO(DEVELOPER): Write the blurImages Function here.

// TODO(DEVELOPER): Write the sendNotification Function here.

Firebase Admin SDK は、Cloud Functions 環境または他の Google Cloud Platform コンテナにデプロイするときに自動的に構成できます。これは、 admin.initializeApp()を引数なしで呼び出すと発生します。

次に、ユーザーがチャット アプリに初めてサインインしたときに実行される関数を追加し、ユーザーを歓迎するチャット メッセージを追加します。

8. 新規ユーザーの歓迎

チャット メッセージの構造

FriendlyChat チャット フィードに投稿されたメッセージは、Cloud Firestore に保存されます。メッセージに使用するデータ構造を見てみましょう。これを行うには、「Hello World」という新しいメッセージをチャットに投稿します。

11f5a676fbb1a69a.png

これは次のように表示されます。

fe6d1c020d0744cf.png

Firebase コンソールで、 [ビルド]セクションの下にある[Firestore データベース]をクリックします。メッセージ コレクションと、作成したメッセージを含む 1 つのドキュメントが表示されます。

442c9c10b5e2b245.png

ご覧のとおり、チャット メッセージは、 messagesコレクションに追加されたnameprofilePicUrltext 、およびtimestamp属性を持つドキュメントとして Cloud Firestore に保存されます。

ウェルカム メッセージの追加

最初の Cloud Function は、新しいユーザーをチャットに歓迎するメッセージを追加します。このために、トリガーfunctions.auth().onCreateを使用できます。これは、ユーザーが Firebase アプリで初めてサインインするたびに関数を実行します。 addWelcomeMessages関数をindex.jsファイルに追加します。

index.js

// Adds a message that welcomes new users into the chat.
exports.addWelcomeMessages = functions.auth.user().onCreate(async (user) => {
  functions.logger.log('A new user signed in for the first time.');
  const fullName = user.displayName || 'Anonymous';

  // Saves the new welcome message into the database
  // which then displays it in the FriendlyChat clients.
  await admin.firestore().collection('messages').add({
    name: 'Firebase Bot',
    profilePicUrl: '/images/firebase-logo.png', // Firebase logo
    text: `${fullName} signed in for the first time! Welcome!`,
    timestamp: admin.firestore.FieldValue.serverTimestamp(),
  });
  functions.logger.log('Welcome message written to database.');
});

この関数を特別なexportsオブジェクトに追加することは、現在のファイルの外部で関数にアクセスできるようにする Node の方法であり、Cloud Functions に必要です。

上記の関数では、「Firebase Bot」によって投稿された新しいウェルカム メッセージをチャット メッセージのリストに追加しています。これを行うには、チャットのメッセージが保存される Cloud Firestore のmessagesコレクションでaddメソッドを使用します。

これは非同期操作であるため、Cloud Functions の実行が早すぎないように、Cloud Firestore がいつ書き込みを終了したかを示すPromiseを返す必要があります。

Cloud Functions をデプロイする

Cloud Functions は、デプロイした後にのみアクティブになります。これを行うには、コマンド ラインでこれを実行します。

firebase deploy --only functions

これは、表示されるコンソール出力です。

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
⚠  functions: missing necessary APIs. Enabling now...
i  env: ensuring necessary APIs are enabled...
⚠  env: missing necessary APIs. Enabling now...
i  functions: waiting for APIs to activate...
i  env: waiting for APIs to activate...
✔  env: all necessary APIs are enabled
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (X.XX KB) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: creating function addWelcomeMessages...
✔  functions[addWelcomeMessages]: Successful create operation. 
✔  functions: all functions deployed successfully!

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlypchat-1234/overview

関数をテストする

関数が正常にデプロイされたら、初めてサインインするユーザーが必要になります。

  1. ホスティング URL ( https://<project-id>.firebaseapp.comの形式) を使用して、ブラウザーでアプリを開きます。
  2. 新しいユーザーで、 [サインイン]ボタンを使用してアプリに初めてサインインします。
  • アプリに既にサインインしている場合は、 Firebase コンソール認証を開き、ユーザーのリストからアカウントを削除できます。その後、再度サインインします。

262535d1b1223c65.png

  1. サインインすると、ウェルカム メッセージが自動的に表示されます。

1c70e0d64b23525b.png

9. 画像のモデレーション

ユーザーはチャットであ​​らゆる種類の画像をアップロードできます。特に公共のソーシャル プラットフォームでは、不快な画像をモデレートすることが常に重要です。 FriendlyChat では、チャットに公開されている画像はGoogle Cloud Storageに保存されます。

Cloud Functions では、 functions.storage().onFinalizeトリガーを使用して、新しい画像のアップロードを検出できます。これは、Cloud Storage で新しいファイルがアップロードまたは変更されるたびに実行されます。

画像をモデレートするには、次のプロセスを実行します。

  1. Cloud Vision APIを使用して、画像が成人向けまたは暴力的としてフラグ付けされているかどうかを確認します。
  2. イメージにフラグが付けられている場合は、実行中の Functions インスタンスにダウンロードします。
  3. ImageMagickを使用して画像をぼかします。
  4. ぼかした画像を Cloud Storage にアップロードします。

Cloud Vision API を有効にする

この関数では Google Cloud Vision API を使用するため、firebase プロジェクトで API を有効にする必要があります。このリンクに従って、Firebase プロジェクトを選択し、API を有効にします。

5c77fee51ec5de49.png

依存関係をインストールする

画像をモデレートするには、Node.js 用の Google Cloud Vision クライアント ライブラリ@google-cloud/visionを使用して、Cloud Vision API を介して画像を実行し、不適切な画像を検出します。

このパッケージを Cloud Functions アプリにインストールするには、次のnpm install --saveコマンドを実行します。これは必ずfunctionsディレクトリから行ってください。

npm install --save @google-cloud/vision@2.4.0

これにより、パッケージがローカルにインストールされ、 package.jsonファイルに宣言された依存関係として追加されます。

依存関係をインポートして構成する

インストールされた依存関係と、このセクションで必要になるいくつかの Node.js コア モジュール ( pathos 、およびfs ) をインポートするには、次の行をindex.jsファイルの先頭に追加します。

index.js

const Vision = require('@google-cloud/vision');
const vision = new Vision.ImageAnnotatorClient();
const {promisify} = require('util');
const exec = promisify(require('child_process').exec);

const path = require('path');
const os = require('os');
const fs = require('fs');

関数は Google Cloud 環境内で実行されるため、Cloud Storage ライブラリと Cloud Vision ライブラリを構成する必要はありません。プロジェクトを使用するように自動的に構成されます。

不適切な画像の検出

functions.storage.onChange Cloud Functions トリガーを使用します。これは、ファイルまたはフォルダーが Cloud Storage バケットで作成または変更されるとすぐにコードを実行します。 blurOffensiveImages関数をindex.jsファイルに追加します。

index.js

// Checks if uploaded images are flagged as Adult or Violence and if so blurs them.
exports.blurOffensiveImages = functions.runWith({memory: '2GB'}).storage.object().onFinalize(
    async (object) => {
      const imageUri = `gs://${object.bucket}/${object.name}`;
      // Check the image content using the Cloud Vision API.
      const batchAnnotateImagesResponse = await vision.safeSearchDetection(imageUri);
      const safeSearchResult = batchAnnotateImagesResponse[0].safeSearchAnnotation;
      const Likelihood = Vision.protos.google.cloud.vision.v1.Likelihood;
      if (Likelihood[safeSearchResult.adult] >= Likelihood.LIKELY ||
          Likelihood[safeSearchResult.violence] >= Likelihood.LIKELY) {
        functions.logger.log('The image', object.name, 'has been detected as inappropriate.');
        return blurImage(object.name);
      }
      functions.logger.log('The image', object.name, 'has been detected as OK.');
    });

関数を実行する Cloud Functions インスタンスの構成をいくつか追加したことに注意してください。 .runWith({memory: '2GB'})では、インスタンスがデフォルトではなく 2GB のメモリを取得するように要求しています。これは、この関数がメモリを集中的に使用するためです。

関数がトリガーされると、Cloud Vision API を介して画像が実行され、アダルトまたは暴力のフラグが付けられているかどうかが検出されます。これらの基準に基づいて画像が不適切であると検出された場合、次に説明するように、 blurImage関数で画像をぼかします。

画像をぼかす

次のblurImage関数をindex.jsファイルに追加します。

index.js

// Blurs the given image located in the given bucket using ImageMagick.
async function blurImage(filePath) {
  const tempLocalFile = path.join(os.tmpdir(), path.basename(filePath));
  const messageId = filePath.split(path.sep)[1];
  const bucket = admin.storage().bucket();

  // Download file from bucket.
  await bucket.file(filePath).download({destination: tempLocalFile});
  functions.logger.log('Image has been downloaded to', tempLocalFile);
  // Blur the image using ImageMagick.
  await exec(`convert "${tempLocalFile}" -channel RGBA -blur 0x24 "${tempLocalFile}"`);
  functions.logger.log('Image has been blurred');
  // Uploading the Blurred image back into the bucket.
  await bucket.upload(tempLocalFile, {destination: filePath});
  functions.logger.log('Blurred image has been uploaded to', filePath);
  // Deleting the local file to free up disk space.
  fs.unlinkSync(tempLocalFile);
  functions.logger.log('Deleted local file.');
  // Indicate that the message has been moderated.
  await admin.firestore().collection('messages').doc(messageId).update({moderated: true});
  functions.logger.log('Marked the image as moderated in the database.');
}

上記の関数では、イメージ バイナリが Cloud Storage からダウンロードされます。次に、ImageMagick のconvertツールを使用して画像をぼかし、ぼかしたバージョンを Storage Bucket に再アップロードします。次に、Cloud Functions インスタンス上のファイルを削除してディスク領域を解放します。これは、同じ Cloud Functions インスタンスが再利用される可能性があり、ファイルがクリーンアップされないとディスク領域が不足する可能性があるためです。最後に、画像がモデレートされたことを示すブール値をチャット メッセージに追加します。これにより、クライアントでメッセージが更新されます。

関数をデプロイする

関数は、展開した後にのみアクティブになります。コマンド ラインで、 firebase deploy --only functionsを実行します。

firebase deploy --only functions

これは、表示されるコンソール出力です。

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (X.XX KB) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: updating function addWelcomeMessages...
i  functions: creating function blurOffensiveImages...
✔  functions[addWelcomeMessages]: Successful update operation.
✔  functions[blurOffensiveImages]: Successful create operation.
✔  functions: all functions deployed successfully!

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview

関数をテストする

関数が正常にデプロイされたら:

  1. ホスティング URL ( https://<project-id>.firebaseapp.comの形式) を使用して、ブラウザーでアプリを開きます。
  2. アプリにサインインしたら、画像をアップロードします。 4db9fdab56703e4a.png
  3. アップロードする最も攻撃的な画像を選択してください (または、この肉食ゾンビを使用することもできます)。しばらくすると、投稿が更新され、ぼやけたバージョンの画像が表示されます。 83dd904fbaf97d2b.png

10. 新しいメッセージの通知

このセクションでは、新しいメッセージが投稿されたときにチャットの参加者に通知を送信する Cloud Function を追加します。

Firebase Cloud Messaging (FCM) を使用すると、さまざまなプラットフォームのユーザーに確実に通知を送信できます。ユーザーに通知を送信するには、FCM デバイス トークンが必要です。私たちが使用しているチャット Web アプリは、ユーザーが新しいブラウザーまたはデバイスでアプリを初めて開いたときに、既にデバイス トークンを収集しています。これらのトークンは、Cloud Firestore のfcmTokensコレクションに保存されます。

ウェブアプリで FCM デバイス トークンを取得する方法を知りたい場合は、 Firebase Web Codelabを参照してください。

通知を送信する

新しいメッセージがいつ投稿されたかを検出するには、 functions.firestore.document().onCreate Cloud Functions トリガーを使用します。このトリガーは、Cloud Firestore の特定のパスで新しいオブジェクトが作成されたときにコードを実行します。 sendNotifications関数をindex.jsファイルに追加します。

index.js

// Sends a notifications to all users when a new message is posted.
exports.sendNotifications = functions.firestore.document('messages/{messageId}').onCreate(
  async (snapshot) => {
    // Notification details.
    const text = snapshot.data().text;
    const payload = {
      notification: {
        title: `${snapshot.data().name} posted ${text ? 'a message' : 'an image'}`,
        body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
        icon: snapshot.data().profilePicUrl || '/images/profile_placeholder.png',
        click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
      }
    };

    // Get the list of device tokens.
    const allTokens = await admin.firestore().collection('fcmTokens').get();
    const tokens = [];
    allTokens.forEach((tokenDoc) => {
      tokens.push(tokenDoc.id);
    });

    if (tokens.length > 0) {
      // Send notifications to all tokens.
      const response = await admin.messaging().sendToDevice(tokens, payload);
      await cleanupTokens(response, tokens);
      functions.logger.log('Notifications have been sent and tokens cleaned up.');
    }
  });

上記の関数では、Cloud Firestore データベースからすべてのユーザーのデバイス トークンを収集し、 admin.messaging().sendToDevice関数を使用してこれらのそれぞれに通知を送信しています。

トークンをクリーンアップする

最後に、有効でなくなったトークンを削除します。これは、ユーザーから取得したトークンがブラウザーまたはデバイスで使用されなくなったときに発生します。たとえば、これは、ユーザーがブラウザ セッションの通知許可を取り消した場合に発生します。これを行うには、次のcleanupTokens関数をindex.jsファイルに追加します。

index.js

// Cleans up the tokens that are no longer valid.
function cleanupTokens(response, tokens) {
 // For each notification we check if there was an error.
 const tokensDelete = [];
 response.results.forEach((result, index) => {
   const error = result.error;
   if (error) {
     functions.logger.error('Failure sending notification to', tokens[index], error);
     // Cleanup the tokens that are not registered anymore.
     if (error.code === 'messaging/invalid-registration-token' ||
         error.code === 'messaging/registration-token-not-registered') {
       const deleteTask = admin.firestore().collection('fcmTokens').doc(tokens[index]).delete();
       tokensDelete.push(deleteTask);
     }
   }
 });
 return Promise.all(tokensDelete);
}

関数をデプロイする

関数はデプロイ後にのみアクティブになります。デプロイするには、コマンド ラインで次のコマンドを実行します。

firebase deploy --only functions

これは、表示されるコンソール出力です。

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (X.XX KB) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: updating function addWelcomeMessages...
i  functions: updating function blurOffensiveImages...
i  functions: creating function sendNotifications...
✔  functions[addWelcomeMessages]: Successful update operation.
✔  functions[blurOffensiveImages]: Successful updating operation.
✔  functions[sendNotifications]: Successful create operation.
✔  functions: all functions deployed successfully!

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview

関数をテストする

  1. 関数が正常にデプロイされたら、ホスティング URL ( https://<project-id>.firebaseapp.comの形式) を使用してブラウザーでアプリを開きます。
  2. アプリに初めてサインインする場合は、プロンプトが表示されたら通知を許可してください。 8b9d0c66dc36153d.png
  3. チャット アプリのタブを閉じるか、別のタブを表示します。通知は、アプリがバックグラウンドにある場合にのみ表示されます。アプリがフォアグラウンドにあるときにメッセージを受信する方法を知りたい場合は、ドキュメントをご覧ください。
  4. 別のブラウザー (またはシークレット ウィンドウ) を使用して、アプリにサインインし、メッセージを投稿します。最初のブラウザに通知が表示されるはずです。 45282ab12b28b926.png

11.おめでとう!

Firebase SDK for Cloud Functions を使用し、サーバー側コンポーネントをチャット アプリに追加しました。

カバーした内容

  • Firebase SDK for Cloud Functions を使用した Cloud Functions のオーサリング。
  • Auth、Cloud Storage、Cloud Firestore イベントに基づいて Cloud Functions をトリガーします。
  • Web アプリに Firebase Cloud Messaging のサポートを追加します。
  • Firebase CLI を使用して Cloud Functions をデプロイします。

次のステップ

もっと詳しく知る

1。概要

この Codelab では、Cloud Functions for Firebase を使用してチャット ウェブアプリに機能を追加し、チャット アプリのユーザーに通知を送信する方法を学習します。

3b1284f5144b54f6.png

学習内容

  • Firebase SDK を使用して Google Cloud Functions を作成します。
  • Auth、Cloud Storage、Cloud Firestore イベントに基づいて Cloud Functions をトリガーします。
  • Web アプリに Firebase Cloud Messaging のサポートを追加します。

必要なもの

  • クレジットカード。 Cloud Functions for Firebase には Firebase Blaze プランが必要です。つまり、クレジット カードを使用して Firebase プロジェクトで課金を有効にする必要があります。
  • WebStormAtomSublimeなど、任意の IDE/テキスト エディター。
  • NodeJS v9 がインストールされたシェル コマンドを実行するためのターミナル。
  • Chrome などのブラウザ。
  • サンプルコード。これについては、次のステップを参照してください。

2. サンプルコードを入手する

コマンド ラインからGitHub リポジトリのクローンを作成します。

git clone https://github.com/firebase/friendlychat

スターター アプリをインポートする

IDE を使用して、 android_studio_folder.pngサンプル コード ディレクトリのcloud-functions-startディレクトリ。このディレクトリには、完全に機能する Chat Web App で構成される Codelab の開始コードが含まれています。

3. Firebase プロジェクトを作成し、アプリをセットアップする

プロジェクトを作成

Firebase Consoleで、 [プロジェクトの追加]をクリックして、 FriendlyChatという名前を付けます。

[プロジェクトの作成]をクリックします。

Blaze プランにアップグレードする

Cloud Functions for Firebase を使用するには、Firebase プロジェクトをBlaze 料金プランにアップグレードする必要があります。これには、クレジット カードまたは別の請求方法を Google Cloud アカウントに追加する必要があります。

Blaze プランのプロジェクトを含むすべての Firebase プロジェクトは、引き続き Cloud Functions の無料使用割り当てにアクセスできます。この Codelab で概説されている手順は、無料利用枠の使用制限内に収まります。ただし、Cloud Functions ビルド イメージをホストするために使用される Cloud Storage から少額の料金 (約 $0.03 ) が発生します。

クレジット カードにアクセスできない場合、または Blaze プランを使い続けることに抵抗がある場合は、ローカル マシンで Cloud Functions を無料でエミュレートできるFirebase Emulator Suiteの使用を検討してください。

Google 認証を有効にする

ユーザーがアプリにサインインできるようにするには、有効にする必要がある Google 認証を使用します。

Firebase コンソールで、 [ビルド] セクション > [認証] > [サインイン方法]タブを開きます (または、ここをクリックしてそこに移動します)。次に、 Googleログイン プロバイダを有効にして[保存]をクリックします。これにより、ユーザーは Google アカウントを使用して Web アプリにサインインできるようになります。

また、アプリの公開名をFriendly Chatに自由に設定してください。

8290061806aacb46.png

クラウド ストレージを有効にする

アプリは Cloud Storage を使用して写真をアップロードします。 Firebase プロジェクトで Cloud Storage を有効にするには、 [ストレージ]セクションにアクセスして[開始]ボタンをクリックします。そこの手順を実行すると、Cloud Storage の場所に使用するデフォルト値が表示されます。その後、 [完了]をクリックします。

ウェブアプリを追加する

Firebase コンソールで、ウェブアプリを追加します。これを行うには、 [Project Settings]に移動し、 [Add app]まで下にスクロールします。プラットフォームとして Web を選択し、Firebase Hosting をセットアップするためのボックスをオンにしてから、アプリを登録し、 [次へ]をクリックして残りの手順を実行し、最後に[Continue to console]をクリックします。

4. Firebase コマンドライン インターフェースをインストールする

Firebase コマンド ライン インターフェース (CLI) を使用すると、Web アプリをローカルで提供し、Web アプリと Cloud Functions をデプロイできます。

CLI をインストールまたはアップグレードするには、次の npm コマンドを実行します。

npm -g install firebase-tools

CLI が正しくインストールされたことを確認するには、コンソールを開いて次を実行します。

firebase --version

Cloud Functions に必要な最新機能がすべて含まれるように、Firebase CLI のバージョンが4.0.0以上であることを確認してください。そうでない場合は、上記のようにnpm install -g firebase-toolsを実行してアップグレードします。

次を実行して、Firebase CLI を承認します。

firebase login

cloud-functions-startディレクトリにいることを確認してから、Firebase プロジェクトを使用するように Firebase CLI を設定します。

firebase use --add

次に、プロジェクト ID を選択し、指示に従います。プロンプトが表示されたら、 codelabなどの任意のエイリアスを選択できます。

5. Web アプリをデプロイして実行する

プロジェクトをインポートして構成したので、初めて Web アプリを実行する準備が整いました。ターミナル ウィンドウを開き、 cloud-functions-startフォルダーに移動し、次を使用して Web アプリを Firebase ホスティングにデプロイします。

firebase deploy --except functions

これは、表示されるコンソール出力です。

i deploying database, storage, hosting
✔  database: rules ready to deploy.
i  storage: checking rules for compilation errors...
✔  storage: rules file compiled successfully
i  hosting: preparing ./ directory for upload...
✔  hosting: ./ folder uploaded successfully
✔ storage: rules file compiled successfully
✔ hosting: 8 files uploaded successfully
i starting release process (may take several minutes)...

✔ Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview
Hosting URL: https://friendlychat-1234.firebaseapp.com

ウェブアプリを開く

最後の行には、ホスティング URL が表示されます。 Web アプリは、https://<project-id>.firebaseapp.com の形式であるこの URL から提供されるようになりました。それを開く。チャット アプリの機能する UI が表示されます。

[SIGN-IN WITH GOOGLE]ボタンを使用してアプリにサインインし、自由にメッセージを追加して画像を投稿してください。

3b1284f5144b54f6.png

新しいブラウザで初めてアプリにサインインする場合は、プロンプトが表示されたら通知を許可してください。 8b9d0c66dc36153d.png

後で通知を有効にする必要があります。

誤って[ブロック]をクリックしてしまった場合は、Chrome オムニバーの URL の左側にある🔒 安全なボタンをクリックし、 [通知]の横にあるバーを切り替えて、この設定を変更できます。

e926868b0546ed71.png

ここで、Firebase SDK for Cloud Functions を使用していくつかの機能を追加します。

6. 関数ディレクトリ

Cloud Functions を使用すると、サーバーをセットアップしなくても、クラウドで実行されるコードを簡単に作成できます。 Firebase Auth、Cloud Storage、および Firebase Firestore データベース イベントに反応する関数を作成する方法について説明します。 Authから始めましょう。

Firebase SDK for Cloud Functions を使用する場合、Functions コードはfunctionsディレクトリの下にあります (デフォルト)。 Functions コードもNode.jsアプリであるため、アプリに関する情報を提供し、依存関係を一覧表示するpackage.json必要です。

簡単にするために、コードを配置するfunctions/index.jsファイルを既に作成しています。先に進む前に、このファイルを自由に調べてください。

cd functions
ls

Node.jsに慣れていない場合は、Codelab を続行する前に、Node.js について詳しく学んでおくと役立ちます。

package.jsonファイルには、 Cloud Functions 用の Firebase SDKFirebase Admin SDK の2 つの必要な依存関係が既にリストされています。それらをローカルにインストールするには、 functionsフォルダーに移動して次を実行します。

npm install

index.jsファイルを見てみましょう。

index.js

/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * ...
 */

// TODO(DEVELOPER): Import the Cloud Functions for Firebase and the Firebase Admin modules here.

// TODO(DEVELOPER): Write the addWelcomeMessage Function here.

// TODO(DEVELOPER): Write the blurImages Function here.

// TODO(DEVELOPER): Write the sendNotification Function here.

必要なモジュールをインポートし、TODO の代わりに 3 つの関数を記述します。必要な Node モジュールのインポートから始めましょう。

7. Cloud Functions と Firebase Admin モジュールをインポートする

この Codelab では 2 つのモジュールが必要になりますfirebase-functions使用すると、Cloud Functions のトリガーとログを書き込むことができますfirebase-adminを使用すると、管理者アクセス権を持つサーバーで Firebase プラットフォームを使用して、Cloud Firestore への書き込みや FCM 通知の送信などのアクションを実行できます。

index.jsファイルで、最初のTODO次のように置き換えます。

index.js

/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * ...
 */

// Import the Firebase SDK for Google Cloud Functions.
const functions = require('firebase-functions');
// Import and initialize the Firebase Admin SDK.
const admin = require('firebase-admin');
admin.initializeApp();

// TODO(DEVELOPER): Write the addWelcomeMessage Function here.

// TODO(DEVELOPER): Write the blurImages Function here.

// TODO(DEVELOPER): Write the sendNotification Function here.

Firebase Admin SDK は、Cloud Functions 環境または他の Google Cloud Platform コンテナにデプロイするときに自動的に構成できます。これは、 admin.initializeApp()を引数なしで呼び出すと発生します。

次に、ユーザーがチャット アプリに初めてサインインしたときに実行される関数を追加し、ユーザーを歓迎するチャット メッセージを追加します。

8. 新規ユーザーの歓迎

チャット メッセージの構造

FriendlyChat チャット フィードに投稿されたメッセージは、Cloud Firestore に保存されます。メッセージに使用するデータ構造を見てみましょう。これを行うには、「Hello World」という新しいメッセージをチャットに投稿します。

11f5a676fbb1a69a.png

これは次のように表示されます。

fe6d1c020d0744cf.png

Firebase コンソールで、 [ビルド]セクションの下にある[Firestore データベース]をクリックします。メッセージ コレクションと、作成したメッセージを含む 1 つのドキュメントが表示されます。

442c9c10b5e2b245.png

ご覧のとおり、チャット メッセージは、 messagesコレクションに追加されたnameprofilePicUrltext 、およびtimestamp属性を持つドキュメントとして Cloud Firestore に保存されます。

ウェルカム メッセージの追加

最初の Cloud Function は、新しいユーザーをチャットに歓迎するメッセージを追加します。このために、トリガーfunctions.auth().onCreateを使用できます。これは、ユーザーが Firebase アプリで初めてサインインするたびに関数を実行します。 addWelcomeMessages関数をindex.jsファイルに追加します。

index.js

// Adds a message that welcomes new users into the chat.
exports.addWelcomeMessages = functions.auth.user().onCreate(async (user) => {
  functions.logger.log('A new user signed in for the first time.');
  const fullName = user.displayName || 'Anonymous';

  // Saves the new welcome message into the database
  // which then displays it in the FriendlyChat clients.
  await admin.firestore().collection('messages').add({
    name: 'Firebase Bot',
    profilePicUrl: '/images/firebase-logo.png', // Firebase logo
    text: `${fullName} signed in for the first time! Welcome!`,
    timestamp: admin.firestore.FieldValue.serverTimestamp(),
  });
  functions.logger.log('Welcome message written to database.');
});

この関数を特別なexportsオブジェクトに追加することは、現在のファイルの外部で関数にアクセスできるようにする Node の方法であり、Cloud Functions に必要です。

上記の関数では、「Firebase Bot」によって投稿された新しいウェルカム メッセージをチャット メッセージのリストに追加しています。これを行うには、チャットのメッセージが保存される Cloud Firestore のmessagesコレクションでaddメソッドを使用します。

これは非同期操作であるため、Cloud Functions の実行が早すぎないように、Cloud Firestore がいつ書き込みを終了したかを示すPromiseを返す必要があります。

Cloud Functions をデプロイする

Cloud Functions は、デプロイした後にのみアクティブになります。これを行うには、コマンド ラインでこれを実行します。

firebase deploy --only functions

これは、表示されるコンソール出力です。

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
⚠  functions: missing necessary APIs. Enabling now...
i  env: ensuring necessary APIs are enabled...
⚠  env: missing necessary APIs. Enabling now...
i  functions: waiting for APIs to activate...
i  env: waiting for APIs to activate...
✔  env: all necessary APIs are enabled
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (X.XX KB) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: creating function addWelcomeMessages...
✔  functions[addWelcomeMessages]: Successful create operation. 
✔  functions: all functions deployed successfully!

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlypchat-1234/overview

関数をテストする

関数が正常にデプロイされたら、初めてサインインするユーザーが必要になります。

  1. ホスティング URL ( https://<project-id>.firebaseapp.comの形式) を使用して、ブラウザーでアプリを開きます。
  2. 新しいユーザーで、 [サインイン]ボタンを使用してアプリに初めてサインインします。
  • アプリに既にサインインしている場合は、 Firebase コンソール認証を開き、ユーザーのリストからアカウントを削除できます。その後、再度サインインします。

262535d1b1223c65.png

  1. After you sign in, a welcome message should be displayed automatically:

1c70e0d64b23525b.png

9. Images moderation

Users can upload all type of images in the chat, and it is always important to moderate offensive images, especially in public social platforms. In FriendlyChat, the images that are being published to the chat are stored into Google Cloud Storage .

With Cloud Functions, you can detect new image uploads using the functions.storage().onFinalize trigger. This will run every time a new file is uploaded or modified in Cloud Storage.

To moderate images, we'll go through the following process:

  1. Check if the image is flagged as Adult or Violent using the Cloud Vision API .
  2. If the image has been flagged, download it on the running Functions instance.
  3. Blur the image using ImageMagick .
  4. Upload the blurred image to Cloud Storage.

Enable the Cloud Vision API

Since we'll be using the Google Cloud Vision API in this function, you must enable the API on your firebase project. Follow this link , then select your Firebase project and enable the API:

5c77fee51ec5de49.png

Install dependencies

To moderate images, we'll use the Google Cloud Vision Client Library for Node.js, @google-cloud/vision , to run images through the Cloud Vision API to detect inappropriate images.

To install this package into your Cloud Functions app, run the following npm install --save command. Make sure that you do this from the functions directory.

npm install --save @google-cloud/vision@2.4.0

This will install the package locally and add them as a declared dependency in your package.json file.

Import and configure dependencies

To import the dependencies that were installed and some Node.js core modules ( path , os and fs ) that we'll need in this section, add the following lines to the top of your index.js file:

index.js

const Vision = require('@google-cloud/vision');
const vision = new Vision.ImageAnnotatorClient();
const {promisify} = require('util');
const exec = promisify(require('child_process').exec);

const path = require('path');
const os = require('os');
const fs = require('fs');

Since your function will run inside a Google Cloud environment, there is no need to configure the Cloud Storage and Cloud Vision libraries: they will be configured automatically to use your project.

Detecting inappropriate images

You'll be using the functions.storage.onChange Cloud Functions trigger, which runs your code as soon as a file or folder is created or modified in a Cloud Storage bucket. Add the blurOffensiveImages Function into your index.js file:

index.js

// Checks if uploaded images are flagged as Adult or Violence and if so blurs them.
exports.blurOffensiveImages = functions.runWith({memory: '2GB'}).storage.object().onFinalize(
    async (object) => {
      const imageUri = `gs://${object.bucket}/${object.name}`;
      // Check the image content using the Cloud Vision API.
      const batchAnnotateImagesResponse = await vision.safeSearchDetection(imageUri);
      const safeSearchResult = batchAnnotateImagesResponse[0].safeSearchAnnotation;
      const Likelihood = Vision.protos.google.cloud.vision.v1.Likelihood;
      if (Likelihood[safeSearchResult.adult] >= Likelihood.LIKELY ||
          Likelihood[safeSearchResult.violence] >= Likelihood.LIKELY) {
        functions.logger.log('The image', object.name, 'has been detected as inappropriate.');
        return blurImage(object.name);
      }
      functions.logger.log('The image', object.name, 'has been detected as OK.');
    });

Note that we added some configuration of the Cloud Functions instance that will run the function. With .runWith({memory: '2GB'}) , we're requesting that the instance gets 2GB of memory rather than the default, because this function is memory intensive.

When the function is triggered, the image is ran through the Cloud Vision API to detect if it is flagged as adult or violent. If the image is detected as inappropriate based on these criteria, we're blurring the image, which is done in the blurImage function as we'll see next.

Blurring the image

Add the following blurImage function in your index.js file:

index.js

// Blurs the given image located in the given bucket using ImageMagick.
async function blurImage(filePath) {
  const tempLocalFile = path.join(os.tmpdir(), path.basename(filePath));
  const messageId = filePath.split(path.sep)[1];
  const bucket = admin.storage().bucket();

  // Download file from bucket.
  await bucket.file(filePath).download({destination: tempLocalFile});
  functions.logger.log('Image has been downloaded to', tempLocalFile);
  // Blur the image using ImageMagick.
  await exec(`convert "${tempLocalFile}" -channel RGBA -blur 0x24 "${tempLocalFile}"`);
  functions.logger.log('Image has been blurred');
  // Uploading the Blurred image back into the bucket.
  await bucket.upload(tempLocalFile, {destination: filePath});
  functions.logger.log('Blurred image has been uploaded to', filePath);
  // Deleting the local file to free up disk space.
  fs.unlinkSync(tempLocalFile);
  functions.logger.log('Deleted local file.');
  // Indicate that the message has been moderated.
  await admin.firestore().collection('messages').doc(messageId).update({moderated: true});
  functions.logger.log('Marked the image as moderated in the database.');
}

In the above function, the image binary is downloaded from Cloud Storage. The image is then blurred using ImageMagick's convert tool, and the blurred version is re-uploaded on the Storage Bucket. Next, we delete the file on the Cloud Functions instance to free up some disk space, and we do this because the same Cloud Functions instance can get re-used and if files are not cleaned up, it could run out of disk space. Finally, we add a boolean to the chat message indicating the image was moderated, and this will trigger a refresh of the message on the client.

Deploy the Function

The Function will only be active after you've deployed it. On the command line, run firebase deploy --only functions :

firebase deploy --only functions

This is the console output you should see:

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (X.XX KB) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: updating function addWelcomeMessages...
i  functions: creating function blurOffensiveImages...
✔  functions[addWelcomeMessages]: Successful update operation.
✔  functions[blurOffensiveImages]: Successful create operation.
✔  functions: all functions deployed successfully!

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview

Test the function

Once the function has deployed successfully:

  1. Open your app in your browser using the hosting URL (in the form of https://<project-id>.firebaseapp.com ).
  2. Once signed into the app, upload an image: 4db9fdab56703e4a.png
  3. Choose your best offensive image to upload (or you can use this flesh eating Zombie !) and after a few moments, you should see your post refresh with a blurred version of the image: 83dd904fbaf97d2b.png

10. New Message Notifications

In this section, you will add a Cloud Function that sends notifications to participants of the chat when a new message is posted.

Using Firebase Cloud Messaging (FCM), you can reliably send notifications to users across platforms. To send a notification to a user, you need their FCM device token. The chat web app that we are using already collects device tokens from users when they open the app for the first time on a new browser or device. These tokens are stored in Cloud Firestore in the fcmTokens collection.

If you would like to learn how to get FCM device tokens on a web app, you can go through the Firebase Web Codelab .

Send notifications

To detect when new messages are posted, you'll be using the functions.firestore.document().onCreate Cloud Functions trigger, which runs your code when a new object is created at a given path of Cloud Firestore. Add the sendNotifications function into your index.js file:

index.js

// Sends a notifications to all users when a new message is posted.
exports.sendNotifications = functions.firestore.document('messages/{messageId}').onCreate(
  async (snapshot) => {
    // Notification details.
    const text = snapshot.data().text;
    const payload = {
      notification: {
        title: `${snapshot.data().name} posted ${text ? 'a message' : 'an image'}`,
        body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
        icon: snapshot.data().profilePicUrl || '/images/profile_placeholder.png',
        click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
      }
    };

    // Get the list of device tokens.
    const allTokens = await admin.firestore().collection('fcmTokens').get();
    const tokens = [];
    allTokens.forEach((tokenDoc) => {
      tokens.push(tokenDoc.id);
    });

    if (tokens.length > 0) {
      // Send notifications to all tokens.
      const response = await admin.messaging().sendToDevice(tokens, payload);
      await cleanupTokens(response, tokens);
      functions.logger.log('Notifications have been sent and tokens cleaned up.');
    }
  });

In the Function above, we are gathering all users' device tokens from the Cloud Firestore database and sending a notification to each of these using the admin.messaging().sendToDevice function.

Cleanup the tokens

Lastly, we want to remove the tokens that are no longer valid. This happens when the token that we once got from the user is not being used by the browser or device anymore. For instance, this happens if the user has revoked the notification permission for the browser session. To do this, add the following cleanupTokens function in your index.js file:

index.js

// Cleans up the tokens that are no longer valid.
function cleanupTokens(response, tokens) {
 // For each notification we check if there was an error.
 const tokensDelete = [];
 response.results.forEach((result, index) => {
   const error = result.error;
   if (error) {
     functions.logger.error('Failure sending notification to', tokens[index], error);
     // Cleanup the tokens that are not registered anymore.
     if (error.code === 'messaging/invalid-registration-token' ||
         error.code === 'messaging/registration-token-not-registered') {
       const deleteTask = admin.firestore().collection('fcmTokens').doc(tokens[index]).delete();
       tokensDelete.push(deleteTask);
     }
   }
 });
 return Promise.all(tokensDelete);
}

Deploy the Function

The function will only be active after you've deployed it, and to deploy it, run this in command line:

firebase deploy --only functions

This is the console output you should see:

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (X.XX KB) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: updating function addWelcomeMessages...
i  functions: updating function blurOffensiveImages...
i  functions: creating function sendNotifications...
✔  functions[addWelcomeMessages]: Successful update operation.
✔  functions[blurOffensiveImages]: Successful updating operation.
✔  functions[sendNotifications]: Successful create operation.
✔  functions: all functions deployed successfully!

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview

Test the function

  1. Once the function has deployed successfully, open your app in your browser using the hosting URL (in the form of https://<project-id>.firebaseapp.com ).
  2. If you sign-in the app for the first time, make sure you allow notifications when prompted: 8b9d0c66dc36153d.png
  3. Close the chat app tab or display a different tab: Notifications appear only if the app is in the background. If you would like to learn how to receive messages while your app is in the foreground, have a look at our documentation .
  4. Using a different browser (or an Incognito window), sign into the app and post a message. You should see a notification displayed by the first browser: 45282ab12b28b926.png

11.おめでとう!

You have used the Firebase SDK for Cloud Functions and added server-side components to a chat app.

What we've covered

  • Authoring Cloud Functions using the Firebase SDK for Cloud Functions.
  • Trigger Cloud Functions based on Auth, Cloud Storage, and Cloud Firestore events.
  • Add Firebase Cloud Messaging support to your web app.
  • Deploy Cloud Functions using the Firebase CLI.

次のステップ

もっと詳しく知る