'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); // Authenticate to Algolia Database. // TODO: Make sure you configure the `algolia.appId` and `algolia.apiKey` Google Cloud environment variables. const algoliasearch = require('algoliasearch'); const client = algoliasearch(functions.config().algolia.appId, functions.config().algolia.apiKey); // Name fo the algolia index for Blog posts content. const ALGOLIA_POSTS_INDEX_NAME = 'blogposts'; // Updates the search index when new blog entries are created or updated. exports.indexentry = functions.database.ref('/blog-posts/{blogid}').onWrite(event => { const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME); const firebaseObject = event.data.val(); firebaseObject.objectID = event.data.key; return index.saveObject(firebaseObject).then( () => event.data.adminRef.child('last_index_timestamp').set( Date.parse(event.timestamp).getTime())); }); // Starts a search query whenever a query is requested (by adding one to the `/search/queries` // element. Search results are then written under `/search/results`. exports.searchentry = functions.database.ref('/search/queries/{queryid}').onWrite(event => { const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME); const query = event.data.val().query;
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.onFollowChanged = functions.database.ref('/follows/{followedUser}').onWrite((change, context) => { let original = change.before.val(); let current = change.after.val(); original = original ? Object.keys(original) : []; current = current ? Object.keys(current) : []; const newFollows = current.filter(follow => original.indexOf(follow) < 0); const removedFollow = original.filter(follow => current.indexOf(follow) < 0); console.log('New Follow: ', newFollows); console.log('Removed Follow: ', removedFollow); let timelineRef = admin.database().ref().child('timeline').child(context.params.followedUser); let timelinePosts = {}; if (removedFollow.length == 1) { console.log('follower removed, remove posts from timeline'); const deletedId = removedFollow[0]; return timelineRef.once('value') .then(timelineSnapshot => { timelinePosts = timelineSnapshot.val() || {}; console.log('Posts: '); console.log(timelinePosts);
const functions = require('firebase-functions'); const request = require('request-promise') exports.indexPostsToElastic = functions.database.ref('/posts/{post_id}') .onWrite(event => { let postData = event.data.val(); let post_id = event.params.post_id; console.log('Indexing post:', postData); let elasticSearchConfig = functions.config().elasticsearch; let elasticSearchUrl = elasticSearchConfig.url + 'posts/post/' + post_id; let elasticSearchMethod = postData ? 'POST' : 'DELETE'; let elasticSearchRequest = { method: elasticSearchMethod, url: elasticSearchUrl, auth:{ username: elasticSearchConfig.username, password: elasticSearchConfig.password, }, body: postData, json: true }; return request(elasticSearchRequest).then(response => { console.log("ElasticSearch response", response); }); });
// Take the text parameter passed to this HTTP endpoint and insert it into the // Realtime Database under the path /messages/:pushId/original exports.addMessage = functions.https.onRequest((req, res) => { // Grab the text parameter. const original = req.query.text; // Push it into the Realtime Database then send a response admin.database().ref('/messages').push({original: original}).then(snapshot => { // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console. res.redirect(303, snapshot.ref); }); }); // Listens for new messages added to /messages/:pushId/original and creates an // uppercase version of the message to /messages/:pushId/uppercase exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') .onWrite(event => { // Grab the current value of what was written to the Realtime Database. const original = event.data.val(); console.log('Uppercasing', event.params.pushId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to the Firebase Realtime Database. // Setting an "uppercase" sibling in the Realtime Database returns a Promise. return event.data.ref.parent.child('uppercase').set(uppercase); }); exports.userJoinedEvent = functions.database.ref('/classMentors/eventParticipants/{eventId}/{userId}/user') .onWrite(event => { // Grab the current value of what was written to the Realtime Database. const original = event.data.val();
// Grab the text parameter. const original = req.query.text; // Todo: Find out why function keeps on getting called if we don't // add to /messages // Push the new message into the Realtime Database using the Firebase Admin SDK. return admin.database().ref('/messages').push({original: original}).then((snapshot) => { // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console. addTweets(original); return res.redirect(303, snapshot.ref.toString()); }); }); // Listens for new messages added to /messages/:pushId/original and creates an // uppercase version of the message to /messages/:pushId/uppercase exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') .onCreate((snapshot, context) => { // Grab the current value of what was written to the Realtime Database. const original = snapshot.val(); console.log('Uppercasing', context.params.pushId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to the Firebase Realtime Database. // Setting an "uppercase" sibling in the Realtime Database returns a Promise. return snapshot.ref.parent.child('uppercase').set(uppercase); }); function addTweets(tweetDate) { var tweetObj = { tweets: [ ],
* You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const functions = require('firebase-functions'); const bigquery = require('@google-cloud/bigquery')(); /** * Writes all logs from the Realtime Database into bigquery. */ exports.addtobigquery = functions.database.ref('/logs/{logid}').onWrite(event => { // TODO: Make sure you set the `bigquery.datasetName` Google Cloud environment variable. const dataset = bigquery.dataset(functions.config().bigquery.datasetname); // TODO: Make sure you set the `bigquery.tableName` Google Cloud environment variable. const table = dataset.table(functions.config().bigquery.tablename); return table.insert({ ID: event.data.key, MESSAGE: event.data.val().message, NUMBER: event.data.val().number }); });
* limitations under the License. */ 'use strict'; const functions = require('firebase-functions'), admin = require('firebase-admin'), logging = require('@google-cloud/logging')(); admin.initializeApp(functions.config().firebase); const stripe = require('stripe')(functions.config().stripe.token), currency = functions.config().stripe.currency || 'USD'; // [START chargecustomer] // Charge the Stripe customer whenever an amount is written to the Realtime database exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite(event => { const val = event.data.val(); // This onWrite will trigger whenever anything is written to the path, so // noop if the charge was deleted, errored out, or the Stripe API returned a result (id exists) if (val === null || val.id || val.error) return null; // Look up the Stripe customer id written in createStripeCustomer return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then(snapshot => { return snapshot.val(); }).then(customer => { // Create a charge using the pushId as the idempotency key, protecting against double charges const amount = val.amount; const idempotency_key = event.params.id; let charge = {amount, currency, customer}; if (val.source !== null) charge.source = val.source; return stripe.charges.create(charge, {idempotency_key}); }).then(response => {
category: transaction.category, date: date.toFbString(), name: transaction.name, note: transaction.note || null, recurring: change.after.key, transfer: transaction.transfer || null }); } date = date.add(transaction.period); } while (date.toFbString() <= transaction.end); return true; } else if (transaction.delete) { let trRef = change.after.ref.parent.parent.child('transactions'); let snapshot = yield trRef.orderByChild('date').startAt(transaction.delete).once('value'); let values = snapshot.val(); for (let key in values) { if (values[key].recurring == change.after.key) yield snapshot.child(key).ref.remove(); } yield change.after.ref.child('delete').remove(); return true; } } return false; }); } exports.handleRecurring = functions.database.ref('/{user}/accounts/{account}/recurring/{key}').onWrite(handleRecurring); exports.createUser = functions.auth.user().onCreate(setupUser); exports.removeUser = functions.auth.user().onDelete(removeUserData); //# sourceMappingURL=index.js.map
var functions = require("firebase-functions"); var admin = require("firebase-admin"); admin.initializeApp(functions.config().firebase); exports.dbAction = functions.database.ref("/input/{uuid}").onWrite(function(event) { console.log("Received event:", event); return event.data.ref.root.child("output/" + event.params.uuid).set(event.data.val()); }); exports.nested = { dbAction: functions.database.ref("/inputNested/{uuid}").onWrite(function(event) { console.log("Received event:", event); return event.data.ref.root.child("output/" + event.params.uuid).set(event.data.val()); }), }; exports.httpsAction = functions.https.onRequest(function(req, res) { res.send(req.body); }); exports.pubsubAction = functions.pubsub.topic("topic1").onPublish(function(event) { console.log("Received event:", event); var uuid = event.data.json; return admin .database() .ref("output/" + uuid) .set(uuid); }); exports.gcsAction = functions.storage.object().onChange(function(event) { console.log("Received event:", event);
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.addMessage = functions.https.onRequest((req, res) => { const original = req.query.text; return admin.database().ref('/mensajes').push({ original: original }).then((snapshot) => { return res.redirect(303, snapshot.ref); }); }); exports.makeUppercase = functions.database.ref('/mensajes/{pushId}/original').onCreate((snap, context) => { /* const authVar = context.auth; // Auth information for the user. const authType = context.authType; // Permissions level for the user. const pathId = context.params.pushId; // The ID in the Path. const eventId = context.eventId; // A unique event ID. const timestamp = context.timestamp; // The timestamp at which the event happened. const eventType = context.eventType; // The type of the event that triggered this function. const resource = context.resource; // The resource which triggered the event. const beforeData = data.before.val(); // data before the write const afterData = data.after.val(); // data after the write */ const pathId = context.params.pushId; const original = snap.val(); const uppercase = original.toUpperCase(); return admin.database().ref('/mensajes/'+pathId+'/uppercase').set(uppercase); });
var functions = require('firebase-functions'); var admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase) exports.createUser = functions.database.ref('/userTemp/{PushId}').onWrite(event => { let userdata = event.data.val(); let key = event.params.key; let root = event.data.ref.root; if (!userdata || userdata.userCreated) { return } return admin.auth().createUser({ email: userdata.uname + '@the-wire.com', emailVerified: true, password: userdata.pass, displayName: userdata.uname, photoURL: "https://previews.123rf.com/images/imagevectors/imagevectors1606/imagevectors160600225/58872992-Blanco-Perfil-de-usuario-icono-en-el-bot-n-azul-aislado-en-blanco-Foto-de-archivo.jpg", disabled: false }) .then(function(userRecord) { // See the UserRecord reference doc for the contents of userRecord. console.log("Successfully created new user:"******"username": userdata.uname, "type": userdata.utype,
* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const functions = require('firebase-functions'); // Max number of lines of the chat history. const MAX_LOG_COUNT = 5; // Removes siblings of the node that element that triggered the function if there are more than MAX_LOG_COUNT. // In this example we'll keep the max number of chat message history to MAX_LOG_COUNT. exports.truncate = functions.database.ref('/chat/{messageid}').onWrite(event => { const parentRef = event.data.ref.parent(); return parentRef.once('value').then(snapshot => { if (snapshot.numChildren() > MAX_LOG_COUNT) { let childCount = 0; const updates = {}; snapshot.forEach(function(child) { if (++childCount < snapshot.numChildren() - MAX_LOG_COUNT) { updates[child.key] = null; } }); // Update the parent. This effectively removes the extra children. return parentRef.update(updates); } }); });
import * as admin from 'firebase-admin' import * as functions from 'firebase-functions' import { to } from '../utils/async' /** * Function to index user data into a public collection for easy access. * Triggered by updates to profile within "users/${userId}" path. Writes data * to users_public path. * @type {functions.CloudFunction} */ export default functions.database .ref('/users/{userId}/displayName') .onWrite(indexUser) /** * Index user's by placing their displayName into the users_public collection * @param {functions.Change} change - Database event from function being * @param {admin.DataSnapshot} change.before - Snapshot of data before change * @param {admin.DataSnapshot} change.after - Snapshot of data after change * @param {functions.EventContext} context - Function context which includes * data about the event. More info in docs: * https://firebase.google.com/docs/reference/functions/functions.EventContext * @return {Promise} Resolves with user's profile */ async function indexUser(change, context) { const { userId } = context.params || {} const publicProfileRef = admin.database().ref(`users_public/${userId}`) // Display Name being deleted if (!change.after.val()) { console.log(
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.sendFeedNotification = functions.database.ref('/user_posts/{pushId}').onWrite(event => { const snapshot = event.data; const text = snapshot.val().content; const payload = { notification: { title: `News Feed : ${snapshot.val().userName} posted a message`, body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '', icon: snapshot.val().userProfileURL, sound: "default" }, data: { title: `News Feed : ${snapshot.val().userName} posted a message`, content: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '', color: '#2196F3' } }; const options = { priority: "high", timeToLive: 60 * 60 * 24 * 7 * 4 }; return admin.messaging().sendToTopic("user_posts", payload, options); }); exports.sendWebConsoleNotification = functions.database.ref('/posts/{pushId}').onWrite(event => {
* See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); /** * Triggers when a user gets a new follower and sends a notification. * * Followers add a flag to `/followers/{followedUid}/{followerUid}`. * Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`. */ exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => { const followerUid = event.params.followerUid; const followedUid = event.params.followedUid; // If un-follow we exit the function. if (!event.data.val()) { return console.log('User ', followerUid, 'un-followed user', followedUid); } console.log('We have a new follower UID:', followerUid, 'for user:'******'value'); // Get the follower profile. const getFollowerProfilePromise = admin.auth().getUser(followerUid); return Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]).then(results => {
* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); const request = require('request-promise'); // Shorten URL exports.shortenUrl = functions.database.ref('/links/{linkID}').onWrite(event => { const snapshot = event.data; if (typeof snapshot.val() !== 'string') { return; } return createShortenerPromise(snapshot); }); // URL to the Google URL Shortener API. function createShortenerRequest(sourceUrl) { return { method: 'POST', uri: `https://www.googleapis.com/urlshortener/v1/url?key=${functions.config().firebase.apiKey}`, body: { longUrl: sourceUrl },
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.onDeleteSector = functions.database.ref('/sectores/{idSector}').onDelete((event) => { const idCeldas = event.data.previous.child('celdas').val(); const root = event.data.adminRef.root; if (idCeldas) { idCeldas.forEach(idCelda => root.child(`/celdas/${idCelda}`).remove()); } }); exports.onDeleteCelda = functions.database.ref('/celdas/{idCelda}').onDelete((event) => { const idSenales = event.data.previous.child('senales').val(); const root = event.data.adminRef.root; if (idSenales) { idSenales.forEach(idSenal => root.child(`/senales/${idSenal}`).remove()); } const idEnclavamientos = event.data.previous.child('enclavamientos').val(); if (idEnclavamientos) { idEnclavamientos.forEach(idEnclavamiento => root.child(`/enclavamientos/${idEnclavamiento}`).remove() ); } });
let functions = require('firebase-functions'); let admin = require('firebase-admin'); admin.initializeApp(); //Fuehre sendNotification function aus, if data is created,updated what ever in userID oder messageID under messages bullet in database exports.sendNotification = functions.database.ref('/messages/{userId}/{messageId}').onWrite((change, context) => { //Receiver is parent, thaints why no child is mentioned //So when value is changing give out value //get the userId of the person receiving the notification because we need to get their token const receiverId = context.params.userId; console.log("receiverId: ", receiverId); //GET USERID AND MESSAGE FROM DATABASE //get the user id of the person who sent the message //if userid changes, get user_id, save as senderID in Database bullet messages const senderId = change.after.child('user_id').val(); console.log("senderId: ", senderId); //also get the message if changes const message = change.after.child('message').val(); console.log("message: ", message); //get the message id. We'll be sending this in the payload //message is also parent const messageId = context.params.messageId; console.log("messageId: ", messageId); //get values from other database branch
'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); const chatApi = require('./chat-api'); const FieldValue = require('firebase-admin').firestore.FieldValue; const chatSupportApi = require('./chat-support-api'); // START SUPPORT exports.createGroupForNewSupportRequest = functions.database.ref('/apps/{app_id}/messages/{recipient_id}').onCreate(event => { // const sender_id = event.params.sender_id; const recipient_id = event.params.recipient_id; const app_id = event.params.app_id;; console.log("recipient_id : " + recipient_id + ", app_id: " + app_id ); // const messageRef = event.data.ref; // console.log('messageRef ' + messageRef); // // const messageKey = event.data.current.key; // const messageKey = messageRef.key; // console.log('messageKey ' + messageKey); const messageWithMessageId = event.data.current.val(); console.log('messageWithMessageId ' + JSON.stringify(messageWithMessageId)); const message = messageWithMessageId[Object.keys(messageWithMessageId)[0]]; //returns 'someVal'
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const functions = require("firebase-functions"); const admin = require("firebase-admin"); admin.initializeApp(); var PlayerStatuses; (function (PlayerStatuses) { PlayerStatuses[PlayerStatuses["WAITING"] = 0] = "WAITING"; PlayerStatuses[PlayerStatuses["PLAYING"] = 1] = "PLAYING"; PlayerStatuses[PlayerStatuses["OFFLINE"] = 2] = "OFFLINE"; PlayerStatuses[PlayerStatuses["NEW"] = 3] = "NEW"; })(PlayerStatuses || (PlayerStatuses = {})); exports.observePlayerChanges = functions.database.ref('players/{pushId}/') .onUpdate((change, context) => __awaiter(this, void 0, void 0, function* () { const player = change.after.val(); switch (player.status) { case PlayerStatuses.OFFLINE: { return cleanUpPlayer(player, context.params.pushId) .catch((reason) => { console.error(`Was unable to clean up the user after they left. Details: ${reason}`); }); } case PlayerStatuses.PLAYING: { break; } case PlayerStatuses.WAITING: { return cleanUpPlayer(player, context.params.pushId) .then(() => {
* limitations under the License. */ 'use strict'; const functions = require('firebase-functions'); const nodemailer = require('nodemailer'); // Configure the email transport using the default SMTP transport and a GMail account. // For other types of transports such as Sendgrid see https://nodemailer.com/transports/ // TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables. const gmailEmail = encodeURIComponent(functions.config().gmail.email); const gmailPassword = encodeURIComponent(functions.config().gmail.password); const mailTransport = nodemailer.createTransport( `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`); // Sends an email confirmation when a user changes his mailing list subscription. exports.sendEmailConfirmation = functions.database.ref('/users/{uid}').onWrite(event => { const snapshot = event.data; const val = snapshot.val(); if (!snapshot.changed('subscribedToMailingList')) { return; } const mailOptions = { from: '"Spammy Corp." <*****@*****.**>', to: val.email }; // The user just subscribed to our newsletter. if (val.subscribedToMailingList) { mailOptions.subject = 'Thanks and Welcome!';
console.log('Image has been blurred'); // Uploading the Blurred image back into the bucket. return bucket.upload(tempLocalFile, { destination: filePath }); }) .then(() => { console.log('Blurred image has been uploaded to', filePath); // Indicate that the message has been moderated. return admin.database().ref(`/messages/${messageId}`).update({ moderated: true }); }) .then(() => { console.log('Marked the image as moderated in the database.'); }); } // Sends a notifications to all users when a new message is posted. exports.sendNotifications = functions.database.ref('/messages/{messageId}').onWrite((event) => { const snapshot = event.data; // Only send a notification when a message has been created. if (snapshot.previous.val()) { return; } // Notification details. const text = snapshot.val().text; const payload = { notification: { title: `${snapshot.val().name} posted ${text ? 'a message' : 'an image'}`, body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '', icon: snapshot.val().photoUrl || '/assets/images/profile_placeholder.png', click_action: `https://${functions.config().firebase.authDomain}` }
//get existing properties with: firebase functions:config:get var moment = require('moment'); var gmailEmail=null; var gmailPassword=null; if (functions.config().gmail) { gmailEmail = encodeURIComponent(functions.config().gmail.email); gmailPassword = encodeURIComponent(functions.config().gmail.password); //const mailTransport = nodemailer.createTransport(`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`); // ################ END EMAIL ################ // } const mailTransport = nodemailer.createTransport(`smtp://postmaster@mg.frontiere21.it:bd2324866fa29bae0a4553c069bdd279@smtp.mailgun.org`); exports.sendEmailNotification = functions.database.ref('/apps/{app_id}/users/{sender_id}/messages/{recipient_id}/{message_id}').onCreate(event => { const message_id = event.params.message_id; const sender_id = event.params.sender_id; const recipient_id = event.params.recipient_id; const app_id = event.params.app_id; const message = event.data.current.val(); // DEBUG console.log("sender_id: "+ sender_id + ", recipient_id : " + recipient_id + ", app_id: " + app_id + ", message_id: " + message_id); // DEBUG console.log('message ' + JSON.stringify(message)); // la funzione termina se si tenta di mandare la notifica ad un gruppo // if (message.channel_type!="direct") { //is a group message // return 0; // }
const functions = require('firebase-functions'); exports.drawWinners = functions.database.ref('/raffles/{raffleId}/drawn') .onWrite(change => { if (change.before.val()) { return Promise.resolve(); } return change.after.ref.parent.child('participants').once('value') .then(snapshot => { let winners = getTicketNames(snapshot.val()); shuffleArray(winners); return change.after.ref.parent.child('winners').set(winners); }) .catch(err => { return change.after.ref.parent.child('winners').set(['Error drawing winners: ' + err.message]); }); }); function getTicketNames(raffle) { let result = []; for (let ticket in raffle) { result.push(raffle[ticket].name); } return result; } /** * Randomize array element order in-place. * Using Fisher-Yates shuffle algorithm. */