FCM push notification with parse server - parse-platform

I need to add FCM push in parse server setting. Please help me.
However when sending from parse. There is some issue between parse server and FCM then.
Here is my index.js, sample code:
var express = require("express");
var ParseServer = require("/usr/lib/node_modules/parse-server").ParseServer;
var ParseDashboard = require("/usr/lib/node_modules/parse-dashboard");
var allowInsecureHTTP = true;
var api = new ParseServer({
databaseURI: "mongodb://127.0.0.1:27017/****",
appId: "****",
masterKey: "****",
serverURL: "http://**.**.**.**:1234/parse",
push: {
ios: {
pfx: "/usr/lib/node_modules/push_crt.p12",
passphrase: "example",
bundleId: "com.example",
production: true
},
android: {
senderId: "123456",
apiKey: "******"
}
}
});
var dashboard = new ParseDashboard(
{
apps: [
{
serverURL: "http://**.**.**.**:1234/parse",
appId: "******",
masterKey: "******",
appName: "MyApp"
}
],
users: [{ user: "admin", pass: "admin" }]
},
allowInsecureHTTP
);
var app = express();
// make the Parse Server available at /parse
app.use("/parse", api);
// make the Parse Dashboard available at /dashboard
app.use("/dashboard", dashboard);
var httpServer = require("http").createServer(app);
httpServer.listen(1234);
Please check and help me. How to add FCM connection inside parse server.

For the ios configuration, I can see 2 errors:
pfx path is probably wrong and that wont work on a server cause its not relative (ie. thats specific to your local computer). Save the file in a "certs" (or whatever you wanna call it) folder where you got the nodejs code. Then update with pfx: __dirname + '/certs/push_crt.p12'
bundleId is not the right key, this should be updated to topic: 'com.example'
For the android config, im not sure what senderId is for, maybe you should get rid of that, unless you are sure you need it.

Related

Graphql subscription in playground during local development throwing "Could not connect to websocket endpoint" in basic nestjs project

This is happening on a simple project during local development, so cloud infrastructure isn't an issue.
This is also happening in the application playground.
My module registration:
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
imports: [YeoConfigModule],
useFactory: (configService: YeoConfigService<AppConfig>) => {
const config: ApolloDriverConfig = {
debug: true,
subscriptions: {
'graphql-ws': true,
},
playground: true,
autoSchemaFile: './apps/event-service/schema.gql',
sortSchema: true,
context: ({ req, res }) => ({ req, res }),
};
const origins = configService.get('CORS_ORIGINS')();
config.cors = { origin: origins, credentials: true };
// config.path = '/apis/event-service/graphql';
return config;
},
inject: [YeoConfigService],
My app startup:
async function bootstrap(): Promise<void> {
const app = await getApp();
await app.listen(process.env.PORT ?? 3600);
}
bootstrap();
My versions:
"graphql-ws": "5.11.2",
"graphql-redis-subscriptions": "2.5.0"
"#apollo/gateway": "2.1.3",
"#nestjs/graphql": "10.1.3",
"graphql": "16.5.0",
Result:
{
"error": "Could not connect to websocket endpoint ws://localhost:3600/graphql. Please check if the endpoint url is correct."
}
Any ideas why this isn't working as expected? I've been reading the nestjs docs up at https://docs.nestjs.com/graphql/subscriptions but there's nothing that I can find about extra setup required other than adding
subscriptions: {
'graphql-ws': true,
},
when registering the graphql module.
For anyone else stumbling upon this, I have started using altair which allows me to specify the ws endpoint as well as the type of connection, among which there is a graphql-ws option.
So I went with it.
If anyone knows how to achieve this using the playground referred in the original answer, happy to mark that one as the right answer over my own.

handleMessageError when registering Teams connector

I'm developing a Microsoft Teams custom app that can add connectors to Teams channels.
My connector has been working fine for a few months now, but a few weeks ago, the ability to register new connectors has stopped working:
After clicking “Save” on the connector configuration page, “loading” shows up until it times out (see the console screenshot below).
When I look in the browser console, I see that the outbound request was actually successful and notifySuccess() was called on the save event, but Teams does not register it (see full JS code below).
Also, a handleMessageError message is emitted, but I could not figure out what the issue is.
I tried this in the native app and in Chrome, and a client tried it in another instance of Teams as well.
Is this a bug or a (undocumented?) change in the Teams API?
Console / UI screenshot
JSON Error Message:
{
"seq": 1615787354693,
"timestamp": 1615793440583,
"flightSettings": {
"Name": "ConnectorFrontEndSettings",
"AriaSDKToken": "d127f72a3abd41c9b9dd94faca947689-d58285e6-3a68-4cab-a458-37b9d9761d35-7033",
"SPAEnabled": true,
"ClassificationFilterEnabled": true,
"ClientRoutingEnabled": true,
"EnableYammerGroupOption": true,
"EnableFadeMessage": false,
"EnableDomainBasedOwaConnectorList": false,
"EnableDomainBasedTeamsConnectorList": false,
"DevPortalSPAEnabled": true,
"ShowHomeNavigationButtonOnConfigurationPage": false,
"DisableConnectToO365InlineDeleteFeedbackPage": true
},
"status": 500,
"clientType": "SkypeSpaces",
"connectorType": "fc0ee140-b62a-4947-9af1-d19a66a00af8",
"name": "handleMessageError"
}
JS code that runs on the connector's configuration page:
const XHR = new XMLHttpRequest();
const subscriptionApiUrl = "https://XYZ.execute-api.us-east-1.amazonaws.com/Prod/subscriptions/";
const channelsApiBaseURL = "https://www.example.com/api/library/v2/channels/";
const defaultChannelParameters = "sorting=latest&language=en&excludeReviews=true";
const url = new URL(window.location.href);
const clientId = url.searchParams.get("clientid");
const clientSecret = url.searchParams.get("clientsecret");
const teamsSettings = {
entityId: "Example",
contentUrl: "https://www.example.com/xyz",
configName: "Example"
};
var saveEvent;
console.log("Example Connector initializing");
microsoftTeams.initialize();
microsoftTeams.settings.setValidityState(true); // make Save button enabled
microsoftTeams.settings.registerOnSaveHandler(handleSaveEvent);
function handleSaveEvent(e) {
saveEvent = e;
microsoftTeams.settings.setSettings(teamsSettings);
microsoftTeams.settings.getSettings(storeSettings);
}
function storeSettings(settings) {
XHR.addEventListener("load", reportSuccess);
XHR.addEventListener("error", reportFailure);
XHR.open("POST", subscriptionApiUrl);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.send(composePayload(settings.webhookUrl));
console.log("Request to store Example Connector sent");
}
function composePayload(webhookUrl) {
return JSON.stringify({
webhookUrl: webhookUrl,
gaChannelUrl: channelsApiBaseURL + document.getElementById("ga-channel-id").value + "/items?" + defaultChannelParameters,
gaClientId: clientId,
gaClientSecret: clientSecret,
cronSchedule: "0 " + document.getElementById("time").value + " * * " + document.getElementById("frequency"),
postNow: document.getElementById("post-now").checked ? true : false
});
}
function reportSuccess(e) {
console.log("Example Connector registered!");
saveEvent.notifySuccess();
}
function reportFailure(e) {
let msg = "Could not connect to subscription API.";
console.log(msg);
saveEvent.notifyFailure(msg);
}
I got the same error. I registered the connector and downloaded the generated manifest.json then packaged (with icons) and tried to sideload the zip. I got the same error when trying to "Save".
I then tried to edit the generated manifest using the App Studio (App Studio -> Import an existing app) and this time I got a meaningful error saying the property needsIdentity is not valid according the schema from the manifest (https://developer.microsoft.com/en-us/json-schemas/teams/v1.3/MicrosoftTeams.schema.json)
Removing this property fixed the issue and I was able to save the connector configuration.
I could not find any documentation about this property. I checked the last version of the schema by now (1.8) and it's not there !!
I created an issue : https://github.com/MicrosoftDocs/msteams-docs/issues/2949

Integrating Microsoft Bot Framework with api.ai

I am working on integrating Microsoft Bot Framework with api.ai. I followed the tutorials here. On coding, I also deployed the bot to Heroku using Heroku command line.
I have used the code as below:
(I have changed my APP ID and Password):
var builder = require('botbuilder');
var restify = require('restify');
var apiairecognizer = require('api-ai-recognizer');
var request = require('request');
//=========================================================
// Bot Setup
//=========================================================
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat bot
var connector = new builder.ChatConnector({
appId: '4c8f3u2b-c56n-4117-bc16-ec31eeb5d25c',
appPassword: '4CBNO8vBGtdcGh9PoiVYottY'
});
var connector = new builder.ConsoleConnector().listen();
var bot = new builder.UniversalBot(connector);
var recognizer = new apiairecognizer("84c78b2c15684c7380c6a74c8fbb343f");
var intents = new builder.IntentDialog({
recognizers: [recognizer]
});
bot.dialog('/',intents);
intents.matches('Flow_1',function(session, args){
var fulfillment = builder.EntityRecognizer.findEntity(args.entities, 'fulfillment');
if (fulfillment){
var speech = fulfillment.entity;
session.send(speech);
}else{
session.send('Sorry...not sure how to respond to that');
}
});
intents.onDefault(function(session){
session.send("Sorry...can you please rephrase?");
});`
My Package.json
{
"name": "nodebot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"api-ai-recognizer": "^1.0.1",
"botbuilder": "^3.8.4",
"restify": "^4.3.0"
}
}
My Procfile
web: node app.js
But after successfully deploying to Heroku, I am seeing the following error:
{"code":"ResourceNotFound","message":"/api/messages does not exist"}
Even when I tried testing the bot from Bot Framework Emulator, I am seeing the below error:
Request to 'http://localhost:3978/api/messages' failed: [404] Not Found
I have following questions:
1. How to successfully integrate api.ai with Framework?
2. How to host it Heroku?
It seems that the api/messages route is not defined. You are missing this line server.post('/api/messages', connector.listen());.
Also, you are defining the connector twice, the ChatConnector and the ConsoleConnector. Make sure to delete the code related to the ConsoleConnector.

Parse Server Simple Mailgun Adapter 'verifyUserEmails' issue

I am using the Parse Server Simple Mailgun Adapter, and my Parse Server is working perfectly on Heroku. I am new to node.js and Express, but I installed the adapter on the root of the Parse Server via:
npm i parse-server-simple-mailgun-adapter
This created a node_modules folder and essentially cloned the Github repository for the Mailgun Adapter. My index.js Parse Server configuration looks like:
var api = new ParseServer({
verifyUserEmails: true,
databaseURI: databaseUri || 'mongodb://DATABASE',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'APPID',
masterKey: process.env.MASTER_KEY || 'MASTERKEY', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'https://SERVER/parse', // Don't forget to change to https if needed
publicServerURL: 'https://SERVER/parse',
fileKey: process.env.FILE_KEY || 'FILEKEY',
push: {
ios: [
{
pfx: 'FILE.p12', // Dev PFX or P12
bundleId: 'BUNDLE',
production: false // Dev
},
{
pfx: 'FILE.p12', // Prod PFX or P12
bundleId: 'BUNDLE',
production: true // Prod
}
]
},
emailAdapter: {
module: 'parse-server-simple-mailgun-adapter',
options: {
fromAddress: 'EMAIL#DOMAIN',
domain: 'DOMAIN',
apiKey: 'KEY',
}
},
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
The server works perfectly when commenting out the verifyUserEmails key. With it, the server will not work. The Mailgun adapter does not work regardless. Any help would be greatly appreciated. Thanks!
Did you set up the email adapter?
Take a look at : https://github.com/ParsePlatform/parse-server
Email verification and password reset
Verifying user email addresses and enabling password reset via email requries an email adapter. As part of the parse-server package we provide an adapter for sending email through Mailgun. To use it, sign up for Mailgun, and add this to your initialization code:
var server = ParseServer({
...otherOptions,
// Enable email verification
verifyUserEmails: true,
// The public URL of your app.
// This will appear in the link that is used to verify email addresses and reset passwords.
// Set the mount path as it is in serverURL
publicServerURL: 'https://example.com/parse',
// Your apps name. This will appear in the subject and body of the emails that are sent.
appName: 'Parse App',
// The email adapter
emailAdapter: {
module: 'parse-server-simple-mailgun-adapter',
options: {
// The address that your emails come from
fromAddress: 'parse#example.com',
// Your domain from mailgun.com
domain: 'example.com',
// Your API key from mailgun.com
apiKey: 'key-mykey',
}
}
});
You can also use other email adapters contributed by the community such as parse-server-sendgrid-adapter or parse-server-mandrill-adapter.
OR
Create your own in cloud code using mailgun-js
https://www.npmjs.com/package/mailgun-js
var api_key = '[SECRET_API_KEY]';
var domain = '[DOMAIN_HERE]';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
Parse.Cloud.define('testemail', function(req, res) {
var data = {
from: 'Excited User <me#samples.mailgun.org>',
to: 'foo#bar.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
res.success('Email Sent!');
});
The real reason why this happens is because you need to include the appName in your server initialization (this drove me crazy for hours)
appName: 'yourAppName',

Mandrill with parse server not working on heroku migration

I have migrate app from parse.com to heroku with mLab and everything works fine except cloud code.
I am using Mandrill for sending email from parse cloud code which is not working with heroku
Here is what I have done so far:
Installed mandrill ~0.1.0 into parse-server-example and push the code to heroku app
Put the cloud code into '/cloud/main.js'
Called the function from iOS app which respond error as:
[Error]: Invalid function. (Code: 141, Version: 1.13.0).
Here is my code script:
Parse.Cloud.define("sendMail", function(request, response) {
var Mandrill = require('mandrill');
Mandrill.initialize('xxxxxx-xxxxx');
Mandrill.sendEmail({
message: {
text: "ffff",
subject: "hello",
from_email: "xxxxx#gmail.com",
from_name: "pqr",
to: [
{
email: "xxxxxxxxxx#gmail.com",
name: "trump"
}
]
},
async: true
},{
success: function(httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
});
But after calling 'sendMail' function I am getting this error:
[Error]: Invalid function. (Code: 141, Version: 1.13.0).
================================== MailGun ==========================
Parse.Cloud.define('hello', function(req, res) {
var api_key = 'key-xxxxxxxxxxxxxx';
var domain = 'smtp.mailgun.org';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: 'xxxxxxxald#gmail.com',
to: 'xxxxx8#gmail.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
//res.success(req.params.name);
});
I had a similar problem with sendgrid, but I finally find a way around the problem.
I think this steps may help you,
Miss some brackets or some code separator? ( try rewritting the entire code in the main.js )
The app is actually running? ( when you type "heroku open" in the terminal you get the default message? ) - if not check step 1.
If the previous are not working, rollback to a safe build and Add the add-ons in the heroku dashboard instead of installing them yourself, then download the git and do any changes to git and then push.
Below I have pasted from cloud code main.js code that is working using Mandrill on heroku parse application to send password recovery e-mail.
in cloud code main.js:
var mandrill_key = process.env.MANDRILL_KEY;
var Mandrill = require('mandrill-api/mandrill');
var mandrill_client = new Mandrill.Mandrill(mandrill_key);
{
success: function(gameScore) {
//alert('New object created with objectId: ' + gameScore.id);
mandrill_client.messages.send(
{
message: {
html: "<p>Hello " + firstUser.get('fullname') + ",</p><p>We received your request to reset your password.</p><p>Your user name is <strong>" + firstUser.get('username') + "</strong>. Please click here to create a new password. This link will expire in one hour after this mail was sent</p><p>If you need additional help, just let us know.</p><p>SampleCompany Support<br>customerservice#example.com</p><p>Copyright Sample Company, Inc. 2014-2017</p>",
subject: "Sample Company Name account recovery",
from_email: "customerservice#example.com",
from_name: "Sample Company Name",
to: [
{
email: firstUser.get('email'),
name: firstUser.get('fullname')
}
]
},
async: true
},
//Success
function(httpResponse) {
console.log(httpResponse);
//alert("Email sent!");
},
//Failure
function(httpResponse) {
console.error(httpResponse);
//alert("Uh oh, something went wrong");
});
},
error: function(gameScore, error) {
console.error(error.message);
//alert('Failed to create new object, with error code: ' + error.message);
},
useMasterKey: true
})

Resources