Firebase cloud functions for crashlytics are not triggering - javascript

So we have a project, in which Crashlytics and analytics are set-up and currently functioning. However I am not able to successfully implement the cloud functions for the three triggers found here : Crashlytics Events.
While testing using other cloud functions such as when there are read/write operations on the database, the functions execute correctly. When deploying the functions folder to firebase, I get no errors in regards to the triggers and the code is very similar to the samples on Github. I have made sure that the SDK is up to date and that I have run npm install in the functions folder for any dependencies.
Here is the JS file:
'use strict';
const functions = require('firebase-functions');
const rp = require('request-promise');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Helper function that posts to Slack about the new issue
const notifySlack = (slackMessage) => {
// See https://api.slack.com/docs/message-formatting on how
// to customize the message payload
return rp({
method: 'POST',
uri: functions.config().slack.webhook_url,
body: {
text: slackMessage,
},
json: true,
});
};
exports.postOnNewIssue = functions.crashlytics.issue().onNewDetected((event) => {
const data = event.data;
const issueId = data.issueId;
const issueTitle = data.issueTitle;
const appName = data.appInfo.appName;
const appPlatform = data.appInfo.appPlatform;
const latestAppVersion = data.appInfo.latestAppVersion;
const slackMessage = `<!here|here> There is a new issue - ${issueTitle} (${issueId}) ` +
`in ${appName}, version ${latestAppVersion} on ${appPlatform}`;
return notifySlack(slackMessage).then(() => {
return console.log(`Posted new issue ${issueId} successfully to Slack`);
});
});
exports.postOnRegressedIssue = functions.crashlytics.issue().onRegressed((event) => {
const data = event.data;
const issueId = data.issueId;
const issueTitle = data.issueTitle;
const appName = data.appInfo.appName;
const appPlatform = data.appInfo.appPlatform;
const latestAppVersion = data.appInfo.latestAppVersion;
const resolvedTime = data.resolvedTime;
const slackMessage = `<!here|here> There is a regressed issue ${issueTitle} (${issueId}) ` +
`in ${appName}, version ${latestAppVersion} on ${appPlatform}. This issue was previously ` +
`resolved at ${new Date(resolvedTime).toString()}`;
return notifySlack(slackMessage).then(() => {
return console.log(`Posted regressed issue ${issueId} successfully to Slack`);
});
});
exports.postOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert((event) => {
const data = event.data;
const issueId = data.issueId;
const issueTitle = data.issueTitle;
const appName = data.appInfo.appName;
const appPlatform = data.appInfo.appPlatform;
const latestAppVersion = data.appInfo.latestAppVersion;
const crashPercentage = data.velocityAlert.crashPercentage;
const slackMessage = `<!here|here> There is an issue ${issueTitle} (${issueId}) ` +
`in ${appName}, version ${latestAppVersion} on ${appPlatform} that is causing ` +
`${parseFloat(crashPercentage).toFixed(2)}% of all sessions to crash.`;
return notifySlack(slackMessage)/then(() => {
console.log(`Posted velocity alert ${issueId} successfully to Slack`);
});
});

When I tried to deploy Crashlytics events, I was greeted with the following error message.
⚠ functions: failed to update function crashlyticsOnRegressed
HTTP Error: 400, The request has errors
⚠ functions: failed to update function crashlyticsOnNew
HTTP Error: 400, The request has errors
⚠ functions: failed to update function crashlyticsOnVelocityAlert
HTTP Error: 400, The request has errors
Sure enough, Cloud Function documentation no longer lists Crashlytics, which used to be under the section Crashlytics triggers. Perhaps Google no longer supports it.

According to this issue, the crashlytics function triggers were deprecated and removed in release 3.13.3 of the firebase-functions SDK.

Related

Sveltekit & Fleek (IPFS) import syntax problem?

I have managed to use fleek to update IPFS via straight javascript. I am now trying to add this functionality to a clean install of a svelteKit app. I think I am having trouble with the syntax around imports, but am not sure what I am doing wrong. When I click the button on the index.svelte I get the following error
Uncaught ReferenceError: require is not defined
uploadIPFS upload.js:3
listen index.mjs:412..........(I truncated the error here)
A few thoughts
I am wondering if it could be working in javascript because it is being called in node (running on the server) but running on the client in svelte?
More Details
The index.svelte file looks like this
<script>
import {uploadIPFS} from '../IPFS/upload'
</script>
<button on:click={uploadIPFS}>
upload to ipfs
</button>
the upload.js file looks like this
export const uploadIPFS = () => {
const fleek = require('#fleekhq/fleek-storage-js');
const apiKey = 'cZsQh9XV5+6Nd1+Bou4OuA==';
const apiSecret = '';
const data = 'pauls test load';
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch (e) {
console.log('error', e);
}
};
testFunctionUpload(data);
};
I have also tried using the other import syntax and when I do I get the following error
500
global is not defined....
import with the other syntax is
import fleekStorage from '#fleekhq/fleek-storage-js';
function uploadIPFS() {
console.log('fleekStorage',fleekStorage)
};
export default uploadIPFS;
*I erased the api secret in the code above. In future I will store these in a .env file.
Even more details (if you need them)
The file below will update IPFS and runs via the command
npm run upload
That file is below. For my version that I used in svelte I simplified the file by removing all the file management and just loading a variable instead of a file (as in the example below)
const fs = require('fs');
const path = require('path');
const fleek = require('#fleekhq/fleek-storage-js');
require('dotenv').config()
const apiKey = process.env.FLEEK_API_KEY;
const apiSecret = process.env.FLEEK_API_SECRET;
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data,
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch(e) {
console.log('error', e);
}
}
// File management not used a my svelte version to keep it simple
const filePath = path.join(__dirname, 'README.md');
fs.readFile(filePath, (err, data) => {
if(!err) {
testFunctionUpload(data);
}
})

How do i fix an error that reads "Cannot find module 'mailosaur'"

i am running a puppeteer script and it seems i have to declare a mailosaur stack for me to proceed with my code. I am running a node.js script in aws cloudwatch. here is me defining the stack, and the code follows suit.
const synthetics = require('Synthetics');
const MailosaurClient = require('mailosaur');
const log = require('SyntheticsLogger');
const puppeteer = require('puppeteer-core');
const url = require('url');
const { v4: uuidv4 } = require('uuid');
await synthetics.executeStep('Assert the email was received', async function () {
const mailosaur = new MailosaurClient(`${process.env.MAILOSAUR_API_KEY}`);
const serverId = ''
const serverDomain = `${serverId}.mailosaur.net`
const searchCriteria = {
sentTo: `${patientEmailAddress}#${serverDomain}`
}
const message = await mailosaur.messages.get(serverId, searchCriteria)
const dom = new JSDOM(message.html.body);
const el = dom.window.document.querySelector('p.em_defaultlink > a');
target = el.href;
});
the error reads
RROR: Canary error:
Error: Cannot find module 'mailosaur'Require stack:- /opt/nodejs/node_modules/daniels-1.js- /var/task/index.js- /var/runtime/UserFunction.js- /var/runtime/index.js Stack: Error: Cannot find module 'mailosaur'
the error says it cannot find the module mailosaur.
you just need to install it.
you need to run
npm install mailosaur;

Facing issue while download file from sharepoint in node.js using sp-download npm package

I am using sp-download to download file from sharepoint in node js. I am executing the below code -
const Download = require('sp-download').Download;
let authContext = await spauth.getAuth(CONFIG.SHAREPOINT.SITES_LINK, {
username: CONFIG.SHAREPOINT.CREDS.USERNAME,
password: CONFIG.SHAREPOINT.CREDS.PASSWORD
});
const download = new Download(authContext);
let filePathToDownload = CONFIG.SHAREPOINT.SITES_LINK + 'sharePointFile File Path';
let saveToPath = 'localFile Path';
download.downloadFile(filePathToDownload, saveToPath)
.then((savedToPath) => {
return true;
})
.catch((error) => {
console.log("error", error);
return false;
});
But code will result below error -
"Error while resolving authentication class"
Any one have any idea?
I've been struggling with it as well and ended up debbuging node_modules/node-sp-auth/lib/src/auth/AuthResolverFactory.js where the error comes from.
Using Office 365 login and pass it should be enough to set authContext as simple object.
const username = CONFIG.SHAREPOINT.CREDS.USERNAME;
const password = CONFIG.SHAREPOINT.CREDS.PASSWORD;
const download = new Download({username, password});
In your case.

Send message to microsoft teams channel using nodejs

I am able to acquire access token but not sure how to send messages because it requires a user and my app is a backend app(nodejs script). On graph explorer, it works.
The code snippet on graph explorer is:
const options = {
authProvider, //I need this value
};
const client = Client.init(options);
const chatMessage = {body: {content: '#.####.#'}};
await client.api('/teams/my-team-id/channels/my-channel-id/messages')
.post(chatMessage);
How do I get authProvider in nodejs?
I tried using MSALAuthenticationProviderOptions but there seems to be an issue (as mentioned in their github repo) by following these steps: https://www.npmjs.com/package/#microsoft/microsoft-graph-client.
You need to run this in the context of an application instead of a user. The Microsoft Graph JavaScript library now supports Azure TokenCredential for acquiring tokens.
const { Client } = require("#microsoft/microsoft-graph-client");
const { TokenCredentialAuthenticationProvider } = require("#microsoft/microsoft-graph-client/authProviders/azureTokenCredentials");
const { ClientSecretCredential } = require("#azure/identity");
const { clientId, clientSecret, scopes, tenantId } = require("./secrets"); // Manage your secret better than this please.
require("isomorphic-fetch");
async function runExample() {
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: [scopes] });
const client = Client.initWithMiddleware({
debugLogging: true,
authProvider,
});
const chatMessage = {body: {content: '#.####.#'}};
const res = await client.api('/teams/my-team-id/channels/my-channel-id/messages')
.post(chatMessage);
console.log(res);
}
runExample().catch((err) => {
console.log("Encountered an error:\n\n", err);
});
This sample came from:
https://github.com/microsoftgraph/msgraph-sdk-javascript/tree/dev/samples/tokenCredentialSamples/ClientCredentialFlow

Javascript functions in firebase

Getting the following error:
"Cannot read property 'userName' of undefined
at Promise.all.then.result"
Also Getting Error
"The behavior for Date objects stored in Firestore is going to change
AND YOUR APP MAY BREAK.
To hide this warning and ensure your app does not break, you need to add the
following code to your app before calling any other Cloud Firestore methods:
const firestore = new Firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
firestore.settings(settings);
With this change, timestamps stored in Cloud Firestore will be read back as
Firebase Timestamp objects instead of as system Date objects. So you will also
need to update code expecting a Date to instead expect a Timestamp. For example:
// Old:
const date = snapshot.get('created_at');
// New:
const timestamp = snapshot.get('created_at');
const date = timestamp.toDate();
Please audit all existing usages of Date when you enable the new behavior. In a
future release, the behavior will change to the new behavior, so if you do not
follow these steps, YOUR APP MAY BREAK."
However in my android project the place where i have defined the "Date" variable i have place the "#ServerTimestamp" on top.
Appreciate the help guys.
Code:
/*eslint-disable */
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.document('notifications/{userEmail}/userNotifications/{notificationId}').onWrite((change, context) => {
const userEmail = context.params.userEmail;
const notificationId = context.params.notificationId;
return admin.firestore().collection("notifications").doc(userEmail).collection("userNotifications").doc(notificationId).get().then(queryResult => {
const senderUserEmail = queryResult.data().senderUserEmail;
const notificationMessage = queryResult.data().notificationMessage;
const fromUser = admin.firestore().collection("users").doc(senderUserEmail).get();
const toUser = admin.firestore().collection("users").doc(userEmail).get();
return Promise.all([fromUser, toUser]).then(result => {
const fromUserName = result[0].data().userName;
const toUserName = result[1].data().userName;
const tokenId = result[1].data().tokenId;
const notificationContent = {
notification: {
title: fromUserName + " is shopping",
body: notificationMessage,
icon: "default"
}
};
return admin.messaging().sendToDevice(tokenId, notificationContent).then(result => {
console.log("Notification sent!");
//admin.firestore().collection("notifications").doc(userEmail).collection("userNotifications").doc(notificationId).delete();
});
});
});
});
Make sure the document you're request actually exists. data() will return undefined if it doesn't. You can use the exists property on the resulting DataSnapshot to check if a document was actually found.

Categories