|
| 1 | +/** |
| 2 | + * Copyright 2023 Google Inc. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import {initializeApp} from "firebase-admin/app"; |
| 18 | +import {getAuth} from "firebase-admin/auth"; |
| 19 | +import {getDatabase} from "firebase-admin/database"; |
| 20 | +import {getMessaging} from "firebase-admin/messaging"; |
| 21 | +import {log, warn} from "firebase-functions/logger"; |
| 22 | +import {onValueWritten} from "firebase-functions/v2/database"; |
| 23 | + |
| 24 | +initializeApp(); |
| 25 | +const auth = getAuth(); |
| 26 | +const db = getDatabase(); |
| 27 | +const messaging = getMessaging(); |
| 28 | + |
| 29 | +/** |
| 30 | + * Triggers when a user gets a new follower and sends a notification. Followers |
| 31 | + * add a flag to `/followers/{followedUid}/{followerUid}`. Users save their |
| 32 | + * device notification tokens to |
| 33 | + * `/users/{followedUid}/notificationTokens/{notificationToken}`. |
| 34 | + */ |
| 35 | +export const sendFollowerNotification = onValueWritten( |
| 36 | + "/followers/{followedUid}/{followerUid}", |
| 37 | + async (event) => { |
| 38 | + // If un-follow we exit the function. |
| 39 | + if (!event.data.after.val()) { |
| 40 | + log(`User ${event.params.followerUid} unfollowed` + |
| 41 | + ` user ${event.params.followedUid} :(`); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + log(`User ${event.params.followerUid} is now following` + |
| 46 | + ` user ${event.params.followedUid}`); |
| 47 | + const tokensRef = |
| 48 | + db.ref(`/users/${event.params.followedUid}/notificationTokens`); |
| 49 | + const notificationTokens = await tokensRef.get(); |
| 50 | + if (!notificationTokens.hasChildren()) { |
| 51 | + log("There are no tokens to send notifications to."); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + log(`There are ${notificationTokens.numChildren()} tokens` + |
| 56 | + " to send notifications to."); |
| 57 | + const followerProfile = await auth.getUser(event.params.followerUid); |
| 58 | + |
| 59 | + // Notification details. |
| 60 | + const notification = { |
| 61 | + title: "You have a new follower!", |
| 62 | + body: (followerProfile.displayName ?? "Someone") + |
| 63 | + " is now following you.", |
| 64 | + image: followerProfile.photoURL ?? "", |
| 65 | + }; |
| 66 | + |
| 67 | + // Send notifications to all tokens. |
| 68 | + const messages = []; |
| 69 | + notificationTokens.forEach((child) => { |
| 70 | + messages.push({ |
| 71 | + token: child.key, |
| 72 | + notification: notification, |
| 73 | + }); |
| 74 | + }); |
| 75 | + const batchResponse = await messaging.sendEach(messages); |
| 76 | + |
| 77 | + if (batchResponse.failureCount < 1) { |
| 78 | + // Messages sent sucessfully. We're done! |
| 79 | + log("Messages sent."); |
| 80 | + return; |
| 81 | + } |
| 82 | + warn(`${batchResponse.failureCount} messages weren't sent.`, |
| 83 | + batchResponse); |
| 84 | + |
| 85 | + // Clean up the tokens that are not registered any more. |
| 86 | + for (const response of batchResponse.responses) { |
| 87 | + if (response.error?.code === |
| 88 | + "messaging/invalid-registration-token" || |
| 89 | + response.error?.code === |
| 90 | + "messaging/registration-token-not-registered") { |
| 91 | + await tokensRef.child(response.messageId).remove(); |
| 92 | + } |
| 93 | + } |
| 94 | + }); |
0 commit comments