Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Agora broadcasting #74

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
.history
.svn/
migrate_working_dir/
functions/.env

# IntelliJ related
*.iml
Expand Down
28 changes: 28 additions & 0 deletions functions/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module.exports = {
env: {
es6: true,
node: true,
},
parserOptions: {
"ecmaVersion": 2018,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
"no-restricted-globals": ["error", "name", "length"],
"prefer-arrow-callback": "error",
"quotes": ["error", "double", {"allowTemplateLiterals": true}],
},
overrides: [
{
files: ["**/*.spec.*"],
env: {
mocha: true,
},
rules: {},
},
],
globals: {},
};
133 changes: 88 additions & 45 deletions functions/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
/**
* Import function triggers from their respective submodules:
*
* const {onCall} = require("firebase-functions/v2/https");
* const {onDocumentWritten} = require("firebase-functions/v2/firestore");
* Create and deploy your first functions:
* https://firebase.google.com/docs/functions/get-started
*
* See a full list of supported triggers at https://firebase.google.com/docs/functions
*/
Expand All @@ -12,23 +10,32 @@ const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

// Create and deploy your first functions
// https://firebase.google.com/docs/functions/get-started
const { onRequest } = require("firebase-functions/v2/https");
const logger = require("firebase-functions/logger");

const dotenv = require("dotenv");
const {
RtcTokenBuilder,
RtcRole,
} = require("agora-token");

dotenv.config();


exports.sendEventNotifications = functions.pubsub.schedule('every 10 minutes').onRun(async (context) => {
const now = admin.firestore.Timestamp.now();
const oneHourLater = new Date(now.toDate().getTime() + 60 * 60 * 1000);
const eventsRef = db.collection('scheduled_streams');
const now = admin.firestore.Timestamp.now();
const oneHourLater = new Date(now.toDate().getTime() + 60 * 60 * 1000);
const eventsRef = db.collection('scheduled_streams');

const snapshot = await eventsRef
.where('date', '<=', oneHourLater)
.where('date', '>=', now)
.get();
.where('date', '<=', oneHourLater)
.where('date', '>=', now)
.get();

if (snapshot.empty) {
console.log('No upcoming events found');
return null;
}
if (snapshot.empty) {
console.log('No upcoming events found');
return null;
}

const messages = [];
snapshot.forEach(async doc => {
Expand All @@ -37,40 +44,40 @@ exports.sendEventNotifications = functions.pubsub.schedule('every 10 minutes').o
const signupsRef = eventsRef.doc(eventId).collection('signups');
const signupSnapshot = await signupsRef.get();

if(!signupSnapshot.empty){
signupSnapshot.forEach(async userDoc => {
const signupData = userDoc.data();
const notified = signupData.notified;
const signupId = userDoc.id;
const userRef = db.collection('users').doc(signupId);
const userSnapshot = await userRef.get();
if (!userSnapshot.empty) {
const fcmToken = userSnapshot.data().fcmToken;
const notify = userSnapshot.data().notify;
if (fcmToken && notify === true && (notified === false || notified === undefined)) {
const message = {
notification: {
title: event.title,
body: `Your event is starting in 1 hour!`,
},
token: fcmToken,
};
messages.push(admin.messaging().send(message));
}
await signupsRef.doc(signupId).update({
notified: true
});
} else {
console.log("No such user found!");
if (!signupSnapshot.empty) {
signupSnapshot.forEach(async userDoc => {
const signupData = userDoc.data();
const notified = signupData.notified;
const signupId = userDoc.id;
const userRef = db.collection('users').doc(signupId);
const userSnapshot = await userRef.get();
if (!userSnapshot.empty) {
const fcmToken = userSnapshot.data().fcmToken;
const notify = userSnapshot.data().notify;
if (fcmToken && notify === true && (notified === false || notified === undefined)) {
const message = {
notification: {
title: event.title,
body: `Your event is starting in 1 hour!`,
},
token: fcmToken,
};
messages.push(admin.messaging().send(message));
}
});
await signupsRef.doc(signupId).update({
notified: true
});
} else {
console.log("No such user found!");
}
});

} else {
console.log('No Signups found');
return null;
console.log('No Signups found');
return null;
}

});
});

try {
const response = await admin.messaging().send(message);
Expand All @@ -80,3 +87,39 @@ exports.sendEventNotifications = functions.pubsub.schedule('every 10 minutes').o
}
return null;
});

exports.generateToken = functions.https.onCall(async (data, context) => {
const appId = process.env.APP_ID;
const appCertificate = process.env.APP_CERTIFICATE;
const channelName = data.channelName;
const uid = data.uid || 0;
const role = RtcRole.PUBLISHER;

const expirationTimeInSeconds = data.expiryTime;
const currentTimestamp = Math.floor(Date.now() / 1000);
const privilegeExpiredTs = currentTimestamp + expirationTimeInSeconds;

if (channelName === undefined || channelName === null) {
throw new functions.https.HttpsError(
"aborted",
"Channel name is required",
);
}

try {
const token = RtcTokenBuilder.buildTokenWithUid(
appId,
appCertificate,
channelName,
uid,
role,
privilegeExpiredTs,
);
return token;
} catch (err) {
throw new functions.https.HttpsError(
"aborted",
"Could not generate token",
);
}
});
Empty file added functions/index.ts
Empty file.
Loading