클라우드 메시징 및 Cloud Functions를 사용하여 웹 앱에 대한 알림 보내기

1. 개요

이 Codelab에서는 Firebase용 Cloud Functions를 사용하여 채팅 앱 사용자에게 알림을 보내 채팅 웹 앱에 기능을 추가하는 방법을 알아봅니다.

3b1284f5144b54f6.png

무엇을 배울 것인가

  • Firebase SDK를 사용하여 Google Cloud Functions를 만듭니다.
  • 인증, Cloud Storage, Cloud Firestore 이벤트를 기반으로 Cloud Functions를 트리거합니다.
  • 웹 앱에 Firebase 클라우드 메시징 지원을 추가하세요.

필요한 것

  • 신용 카드. Firebase용 Cloud Functions에는 Firebase Blaze 요금제가 필요합니다. 즉, 신용카드를 사용하여 Firebase 프로젝트에서 결제를 활성화해야 합니다.
  • WebStorm , Atom 또는 Sublime 등 원하는 IDE/텍스트 편집기.
  • NodeJS v9가 설치된 상태에서 셸 명령을 실행하는 터미널입니다.
  • Chrome과 같은 브라우저.
  • 샘플 코드입니다. 이에 대해서는 다음 단계를 참조하세요.

2. 샘플 코드 받기

명령줄에서 GitHub 저장소를 복제합니다.

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

시작 앱 가져오기

IDE를 사용하여 다음을 열거나 가져옵니다. android_studio_folder.png 샘플 코드 디렉터리의 cloud-functions-start 디렉터리입니다. 이 디렉터리에는 완전한 기능을 갖춘 Chat 웹 앱으로 구성된 Codelab의 시작 코드가 포함되어 있습니다.

3. Firebase 프로젝트 생성 및 앱 설정

프로젝트 생성

Firebase 콘솔 에서 프로젝트 추가를 클릭하고 FriendlyChat 이라고 이름을 지정하세요.

프로젝트 생성 을 클릭합니다.

Blaze 요금제로 업그레이드하세요

Firebase용 Cloud Functions를 사용하려면 Firebase 프로젝트를 Blaze 요금제 로 업그레이드해야 합니다. 이를 위해서는 Google Cloud 계정에 신용카드나 다른 결제 수단을 추가해야 합니다.

Blaze 요금제를 포함한 모든 Firebase 프로젝트는 계속해서 Cloud Functions의 무료 사용 할당량에 액세스할 수 있습니다. 이 Codelab에 설명된 단계는 무료 등급 사용량 한도에 속합니다. 하지만 Cloud Functions 빌드 이미지를 호스팅하는 데 사용되는 Cloud Storage에서는 소액( 약 $0.03 )의 요금이 청구됩니다.

신용카드에 액세스할 수 없거나 Blaze 요금제를 계속 사용하는 것이 불편한 경우 로컬 컴퓨터에서 Cloud Functions를 무료로 에뮬레이션할 수 있는 Firebase 에뮬레이터 제품군을 사용해 보세요.

Google 인증 활성화

사용자가 앱에 로그인할 수 있도록 활성화해야 하는 Google 인증을 사용합니다.

Firebase 콘솔에서 빌드 섹션 > 인증 > 로그인 방법 탭을 엽니다(또는 여기를 클릭하여 이동하세요). 그런 다음 Google 로그인 공급자를 활성화하고 저장을 클릭합니다. 이렇게 하면 사용자가 Google 계정으로 웹 앱에 로그인할 수 있습니다.

또한 앱의 공개 이름을 Friendly Chat 으로 자유롭게 설정하세요.

8290061806aacb46.png

클라우드 저장소 활성화

앱은 Cloud Storage를 사용하여 사진을 업로드합니다. Firebase 프로젝트에서 Cloud Storage를 활성화하려면 저장소 섹션으로 이동하여 시작하기 버튼을 클릭하세요. 해당 단계를 진행하면 Cloud Storage 위치에 사용할 기본값이 있습니다. 나중에 완료를 클릭하세요.

웹 앱 추가

Firebase 콘솔에서 웹 앱을 추가합니다. 그렇게 하려면 프로젝트 설정 으로 이동하여 앱 추가 까지 아래로 스크롤하세요. 플랫폼으로 웹을 선택하고 Firebase 호스팅 설정 상자를 선택한 다음 앱을 등록하고 나머지 단계를 위해 다음을 클릭하고 마지막으로 콘솔로 계속을 클릭합니다.

4. Firebase 명령줄 인터페이스 설치

Firebase 명령줄 인터페이스(CLI)를 사용하면 웹 앱을 로컬로 제공하고 웹 앱과 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. 웹앱 배포 및 실행

이제 프로젝트를 가져오고 구성했으므로 처음으로 웹 앱을 실행할 준비가 되었습니다! 터미널 창을 열고 cloud-functions-start 폴더로 이동한 후 다음을 사용하여 웹 앱을 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이 표시되어야 합니다. 이제 웹 앱은 https://<project-id>.firebaseapp.com 형식의 이 URL에서 제공되어야 합니다. 열어 봐. 채팅 앱의 작동 UI가 표시됩니다.

GOOGLE로 로그인 버튼을 사용하여 앱에 로그인하고 자유롭게 메시지를 추가하고 이미지를 게시하세요.

3b1284f5144b54f6.png

새 브라우저에서 처음으로 앱에 로그인하는 경우 메시지가 표시되면 알림을 허용해야 합니다. 8b9d0c66dc36153d.png

나중에 알림을 활성화해야 합니다.

실수로 차단을 클릭한 경우 Chrome 옴니바의 URL 왼쪽에 있는 🔒 보안 버튼을 클릭하고 알림 옆의 표시줄을 전환하여 이 설정을 변경할 수 있습니다.

e926868b0546ed71.png

이제 Cloud Functions용 ​​Firebase SDK를 사용하여 몇 가지 기능을 추가하겠습니다.

6. 기능 디렉토리

Cloud Functions를 사용하면 서버를 설정할 필요 없이 클라우드에서 실행되는 코드를 쉽게 가질 수 있습니다. Firebase 인증, Cloud Storage, Firebase Firestore 데이터베이스 이벤트에 반응하는 함수를 빌드하는 방법을 살펴보겠습니다. 인증부터 시작해 보겠습니다.

Cloud Functions용 ​​Firebase SDK를 사용하는 경우 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 라는 두 가지 필수 종속 항목이 이미 나열되어 있습니다. 로컬로 설치하려면 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 대신 세 개의 함수를 작성합니다. 필요한 Node 모듈을 가져오는 것부터 시작해 보겠습니다.

7. Cloud Functions 및 Firebase 관리 모듈 가져오기

이 Codelab에는 두 가지 모듈이 필요합니다. 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 콘솔의 Build 섹션에서 Firestore Database를 클릭합니다. 메시지 컬렉션과 작성한 메시지가 포함된 문서 하나가 표시됩니다.

442c9c10b5e2b245.png

보시다시피 채팅 메시지는 messages 컬렉션에 name , profilePicUrl , text , timestamp 속성이 추가된 문서로 Cloud Firestore에 저장됩니다.

환영 메시지 추가

첫 번째 Cloud 함수는 채팅에 새로운 사용자를 환영하는 메시지를 추가합니다. 이를 위해 사용자가 Firebase 앱에 처음으로 로그인할 때마다 함수를 실행하는 트리거 functions.auth().onCreate 사용할 수 있습니다. index.js 파일에 addWelcomeMessages 함수를 추가하세요.

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 Firestore가 쓰기를 완료한 시점을 나타내는 Promise를 반환하여 Cloud Functions가 너무 일찍 실행되지 않도록 해야 합니다.

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 핵심 모듈( path , osfs )을 가져오려면 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 라이브러리를 구성할 필요가 없습니다. 프로젝트를 사용하도록 자동으로 구성됩니다.

부적절한 이미지 감지

Cloud Storage 버킷에서 파일이나 폴더가 생성되거나 수정되는 즉시 코드를 실행하는 functions.storage.onChange Cloud Functions 트리거를 사용하게 됩니다. index.js 파일에 blurOffensiveImages 함수를 추가하세요.

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 함수에서 수행됩니다.

이미지 흐리게 하기

index.js 파일에 다음 blurImage 함수를 추가하세요.

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 도구를 사용하여 이미지가 흐려지고 흐릿한 버전이 스토리지 버킷에 다시 업로드됩니다. 다음으로 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 함수를 추가합니다.

FCM( Firebase Cloud Messaging )을 사용하면 플랫폼 전반에 걸쳐 사용자에게 안정적으로 알림을 보낼 수 있습니다. 사용자에게 알림을 보내려면 FCM 장치 토큰이 필요합니다. 우리가 사용하고 있는 채팅 웹 앱은 사용자가 새 브라우저나 기기에서 처음으로 앱을 열 때 이미 사용자로부터 기기 토큰을 수집합니다. 이러한 토큰은 fcmTokens 컬렉션의 Cloud Firestore에 저장됩니다.

웹 앱에서 FCM 기기 토큰을 얻는 방법을 알아보려면 Firebase 웹 Codelab을 살펴보세요.

알림 보내기

새 메시지가 게시되는 시기를 감지하려면 Cloud Firestore의 특정 경로에 새 객체가 생성될 때 코드를 실행하는 functions.firestore.document().onCreate Cloud Functions 트리거를 사용하게 됩니다. index.js 파일에 sendNotifications 함수를 추가합니다.

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 함수를 사용하여 이들 각각에 알림을 보냅니다.

토큰 정리

마지막으로 더 이상 유효하지 않은 토큰을 제거하려고 합니다. 이는 사용자로부터 받은 토큰이 더 이상 브라우저나 장치에서 사용되지 않을 때 발생합니다. 예를 들어, 사용자가 브라우저 세션에 대한 알림 권한을 취소한 경우 이런 일이 발생합니다. 이렇게 하려면 index.js 파일에 다음 cleanupTokens 함수를 추가하세요.

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. 축하합니다!

Cloud Functions용 ​​Firebase SDK를 사용하고 채팅 앱에 서버 측 구성요소를 추가했습니다.

우리가 다룬 내용

  • Cloud Functions용 ​​Firebase SDK를 사용하여 Cloud Functions를 작성합니다.
  • 인증, Cloud Storage, Cloud Firestore 이벤트를 기반으로 Cloud Functions를 트리거합니다.
  • 웹 앱에 Firebase 클라우드 메시징 지원을 추가하세요.
  • Firebase CLI를 사용하여 Cloud Functions를 배포합니다.

다음 단계

더 알아보기