1. 概述
在此 Codelab 中,您將了解如何使用 Cloud Functions for Firebase 通過向聊天應用的用戶發送通知來向聊天 Web 應用添加功能。
你將學到什麼
- 使用 Firebase SDK 創建 Google Cloud Functions。
- 基於身份驗證、Cloud Storage 和 Cloud Firestore 事件觸發 Cloud Functions。
- 向您的 Web 應用程序添加 Firebase 雲消息傳遞支持。
你需要什麼
2. 獲取示例代碼
從命令行克隆GitHub 存儲庫:
git clone https://github.com/firebase/friendlychat
導入入門應用程序
使用 IDE 打開或導入示例代碼目錄中的
cloud-functions-start
目錄。此目錄包含 Codelab 的起始代碼,其中包含功能齊全的聊天 Web 應用程序。
3. 創建 Firebase 項目並設置您的應用
創建項目
在Firebase 控制台中,單擊“添加項目”並將其命名為“FriendlyChat” 。
單擊“創建項目” 。
升級至 Blaze 計劃
為了使用 Cloud Functions for Firebase,您必須將 Firebase 項目升級到Blaze 計費計劃。這需要您將信用卡或其他結算方式添加到您的 Google Cloud 帳戶。
所有 Firebase 項目(包括 Blaze 計劃中的項目)仍然可以使用 Cloud Functions 的免費使用配額。此 Codelab 中概述的步驟將屬於免費套餐的使用限制範圍。但是,您會看到用於託管 Cloud Functions 構建映像的 Cloud Storage 收取少量費用(約 0.03 美元)。
如果您無法使用信用卡或不願意繼續使用 Blaze 計劃,請考慮使用Firebase 模擬器套件,它允許您在本地計算機上免費模擬 Cloud Functions。
啟用谷歌身份驗證
為了讓用戶登錄應用程序,我們將使用需要啟用的 Google 身份驗證。
在 Firebase 控制台中,打開“構建”部分 > “身份驗證” > “登錄方法”選項卡(或單擊此處轉到那裡)。然後,啟用Google Sign-in Provider 並單擊Save 。這將允許用戶使用其 Google 帳戶登錄網絡應用程序。
另外,請隨意將您的應用程序的面向公眾的名稱設置為Friendly Chat :
啟用雲存儲
該應用程序使用雲存儲上傳圖片。要在 Firebase 項目上啟用 Cloud Storage,請訪問“存儲”部分並單擊“開始”按鈕。完成那裡的步驟,對於雲存儲位置,將有一個要使用的默認值。之後單擊“完成” 。
添加網絡應用程序
在 Firebase 控制台上,添加一個 Web 應用。為此,請轉到“項目設置”並向下滾動到“添加應用程序” 。選擇 Web 作為平台並選中用於設置 Firebase 託管的複選框,然後註冊應用程序並單擊“下一步”執行其餘步驟,最後單擊“繼續控制台” 。
4. 安裝 Firebase 命令行界面
Firebase 命令行界面 (CLI) 將允許您在本地提供 Web 應用程序並部署 Web 應用程序和 Cloud Functions。
要安裝或升級 CLI,請運行以下 npm 命令:
npm -g install firebase-tools
要驗證 CLI 是否已正確安裝,請打開控制台並運行:
firebase --version
確保 Firebase CLI 的版本高於4.0.0 ,以便它具有 Cloud Functions 所需的所有最新功能。如果沒有,請運行npm install -g firebase-tools
進行升級,如上所示。
通過運行以下命令來授權 Firebase CLI:
firebase login
確保您位於cloud-functions-start
目錄中,然後設置 Firebase CLI 以使用您的 Firebase 項目:
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。現在應該從此 URL 提供 Web 應用程序,其格式應為 https://<project-id>.firebaseapp.com。打開它。您應該會看到聊天應用程序的功能 UI。
使用“使用 GOOGLE 登錄”按鈕登錄應用程序,並隨意添加一些消息和發布圖像:
如果您首次在新瀏覽器上登錄應用程序,請確保在出現提示時允許通知:
我們稍後需要啟用通知。
如果您不小心單擊了“阻止” ,則可以通過單擊 Chrome 多功能欄中 URL 左側的“安全”按鈕並切換“通知”旁邊的欄來更改此設置:
現在,我們將使用 Firebase SDK for Cloud Functions 添加一些功能。
6. 函數目錄
Cloud Functions 允許您輕鬆擁有在雲中運行的代碼,而無需設置服務器。我們將逐步介紹如何構建對 Firebase Auth、Cloud Storage 和 Firebase Firestore 數據庫事件做出反應的函數。讓我們從 Auth 開始。
使用適用於 Cloud Functions 的 Firebase SDK 時,您的 Functions 代碼將位於functions
目錄下(默認情況下)。您的 Functions 代碼也是Node.js應用程序,因此需要一個package.json
來提供有關您的應用程序的一些信息並列出依賴項。
為了讓您更輕鬆,我們已經創建了您的代碼所在的functions/index.js
文件。在繼續之前請隨意檢查此文件。
cd functions
ls
如果您不熟悉Node.js ,在繼續 Codelab 之前了解更多相關信息將會有所幫助。
package.json
文件已列出兩個必需的依賴項: Firebase SDK for Cloud Functions和Firebase Admin SDK 。要在本地安裝它們,請轉到functions
文件夾並運行:
npm install
現在讓我們看一下index.js
文件:
索引.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。讓我們從導入所需的 Node 模塊開始。
7. 導入 Cloud Functions 和 Firebase 管理模塊
在此 Codelab 期間將需要兩個模塊: firebase-functions
支持寫入 Cloud Functions 觸發器和日誌,而firebase-admin
支持在具有管理員訪問權限的服務器上使用 Firebase 平台來執行操作,例如寫入 Cloud Firestore 或發送 FCM 通知。
在index.js
文件中,將第一個TODO
替換為以下內容:
索引.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.
當部署到 Cloud Functions 環境或其他 Google Cloud Platform 容器時,Firebase Admin SDK 可以自動配置,當我們不帶參數調用admin.initializeApp()
時,就會發生這種情況。
現在,讓我們添加一個在用戶首次登錄聊天應用程序時運行的函數,並且我們將添加一條聊天消息來歡迎用戶。
8. 歡迎新用戶
聊天消息結構
發佈到FriendlyChat聊天源的消息存儲在Cloud Firestore中。讓我們看一下用於消息的數據結構。為此,請在聊天中發布一條新消息,內容為“Hello World”:
這應該顯示為:
在 Firebase 控制台中,單擊“構建”部分下的“Firestore 數據庫” 。您應該會看到消息集合和一份包含您所寫消息的文檔:
如您所見,聊天消息作為文檔存儲在 Cloud Firestore 中,並將name
、 profilePicUrl
、 text
和timestamp
屬性添加到messages
集合中。
添加歡迎消息
第一個雲功能添加了一條歡迎新用戶加入聊天的消息。為此,我們可以使用觸發器functions.auth().onCreate
,它會在用戶每次在Firebase應用程序中首次登錄時運行該函數。將addWelcomeMessages
函數添加到您的index.js
文件中:
索引.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
方法來實現此目的,這是存儲聊天消息的位置。
由於這是一個異步操作,我們需要返回Promise來指示 Cloud Firestore 何時完成寫入,以便 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
測試功能
成功部署該功能後,您將需要有一個首次登錄的用戶。
- 使用託管 URL(格式為
https://<project-id>.firebaseapp.com
)在瀏覽器中打開您的應用程序。 - 對於新用戶,請使用“登錄”按鈕首次登錄您的應用程序。
- 如果您已經登錄應用程序,則可以打開Firebase 控制台身份驗證並從用戶列表中刪除您的帳戶。然後,再次登錄。
- 登錄後,應自動顯示歡迎消息:
9. 圖片審核
用戶可以在聊天中上傳所有類型的圖像,因此控制攻擊性圖像始終很重要,尤其是在公共社交平台上。在FriendlyChat中,發佈到聊天的圖像存儲在Google Cloud Storage中。
借助 Cloud Functions,您可以使用functions.storage().onFinalize
觸發器檢測新的圖像上傳。每次在 Cloud Storage 中上傳或修改新文件時,都會運行該命令。
為了審核圖像,我們將執行以下過程:
- 使用Cloud Vision API檢查圖像是否被標記為成人或暴力。
- 如果圖像已被標記,請將其下載到正在運行的 Functions 實例上。
- 使用ImageMagick模糊圖像。
- 將模糊圖像上傳到雲存儲。
啟用雲視覺API
由於我們將在此函數中使用 Google Cloud Vision API,因此您必須在 firebase 項目上啟用該 API。點擊此鏈接,然後選擇您的 Firebase 項目並啟用 API:
安裝依賴項
為了審核圖像,我們將使用適用於 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 核心模塊( path
、 os
和fs
),請將以下行添加到index.js
文件的頂部:
索引.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
文件中:
索引.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
函數中完成。
圖像模糊
在您的index.js
文件中添加以下blurImage
函數:
索引.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
工具對圖像進行模糊處理,並將模糊版本重新上傳到存儲桶上。接下來,我們刪除 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
測試功能
函數部署成功後:
- 使用託管 URL(格式為
https://<project-id>.firebaseapp.com
)在瀏覽器中打開您的應用程序。 - 登錄應用程序後,上傳圖像:
- 選擇要上傳的最佳攻擊性圖像(或者您可以使用這個食肉殭屍!),過了一會兒,您應該會看到您的帖子刷新,並顯示圖像的模糊版本:
10. 新消息通知
在此部分中,您將添加一個雲函數,用於在發布新消息時向聊天參與者發送通知。
使用Firebase Cloud Messaging (FCM),您可以跨平台可靠地向用戶發送通知。要向用戶發送通知,您需要他們的 FCM 設備令牌。當用戶在新的瀏覽器或設備上首次打開該應用程序時,我們正在使用的聊天 Web 應用程序已經收集了用戶的設備令牌。這些令牌存儲在 Cloud Firestore 中的fcmTokens
集合中。
如果您想了解如何在 Web 應用程序上獲取 FCM 設備令牌,可以訪問Firebase Web Codelab 。
發送通知
要檢測何時發布新消息,您將使用functions.firestore.document().onCreate
Cloud Functions 觸發器,該觸發器會在 Cloud Firestore 的給定路徑創建新對象時運行您的代碼。將sendNotifications
函數添加到您的index.js
文件中:
索引.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
函數向每個用戶發送通知。
清理令牌
最後,我們要刪除不再有效的令牌。當我們曾經從用戶那裡獲得的令牌不再被瀏覽器或設備使用時,就會發生這種情況。例如,如果用戶撤銷了瀏覽器會話的通知權限,就會發生這種情況。為此,請在index.js
文件中添加以下cleanupTokens
函數:
索引.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
測試功能
- 函數部署成功後,使用託管 URL(格式為
https://<project-id>.firebaseapp.com
)在瀏覽器中打開您的應用程序。 - 如果您是第一次登錄應用程序,請確保在出現提示時允許通知:
- 關閉聊天應用程序選項卡或顯示其他選項卡:僅當應用程序位於後台時才會顯示通知。如果您想了解如何在應用程序位於前台時接收消息,請查看我們的文檔。
- 使用不同的瀏覽器(或隱身窗口)登錄應用程序並發布消息。您應該會看到第一個瀏覽器顯示的通知:
11. 恭喜!
您已使用適用於 Cloud Functions 的 Firebase SDK 並向聊天應用添加了服務器端組件。
我們涵蓋的內容
- 使用 Firebase SDK for Cloud Functions 編寫 Cloud Functions。
- 根據身份驗證、Cloud Storage 和 Cloud Firestore 事件觸發 Cloud Functions。
- 向您的 Web 應用程序添加 Firebase 雲消息傳遞支持。
- 使用 Firebase CLI 部署 Cloud Functions。
下一步
- 了解其他 Cloud Function 觸發器類型。
- 將 Firebase 和 Cloud Functions 與您自己的應用結合使用。