Integration of node-whatsapi in meteor - meteor

I want to be able to nose whatsapi in meteor. I am using
latest stable meteor
node-whatsapi
arunoda´s meteorhacks:npm
and can get the past the basics:
On meteor server startup, I have:
whatsapi = Meteor.npmRequire('whatsapi');
wa = whatsapi.createAdapter({
msisdn: '....',
username: '....',
password: '....',
ccode: '....'
});
wa.connect(function connected(err) {
if (err) {console.log(err); return;}
console.log('Connected');
wa.login(logged);
});
function logged(err) {
if (err) {console.log(err); return;}
console.log('Logged in');
wa.sendIsOnline();
};
... which let me send and receive messages with a method call to
wa.sendMessage(recipient, content, function(err, id) {
if (err) {console.log(err.message); return;}
console.log('Server received message %s', id);
});
The code bellow also works, logging received messages on the console. This sits inside server Meteor.startup:
wa.on('receivedMessage', function(message) {
console.log("From: " + message.from);
console.log(message.body);
});
My problem is that when I try to add store message.from or message.body into a collection, meteor gives me "Meteor code must always run within a Fiber" error")
wa.on('receivedMessage', function(message) {
console.log("From: " + message.from);
console.log(message.body);
Recipients.insert({msgfrom: message.from});
});
Help!

Use Meteor.bindEnvironment to wrap any callback given out by your npm module. It will wrap the callback into a 'Fiber' so you can run Meteor code in it.
For example:
wa.on('receivedMessage', Meteor.bindEnvironment(function(message) {
console.log("From: " + message.from);
console.log(message.body);
Recipients.insert({msgfrom: message.from});
}));
What it does essentially is place the code in the callback into a Fiber.

Related

Mail Not Received

I try to send the mail using Meteor with Email package but mail not received
In client side i used this code
Meteor.call('sendEmail', 'xxx#sss.com', 'aaa#aat.com','Hello from Meteor!', 'This is a test of Email.send.');
In server side
Meteor.methods ({
sendEmail(to, from, subject, text) {
this.unblock();
Email.send({ to, from, subject, text });
}
});
In smptp.js
Meteor.startup(function () {
process.env.MAIL_URL = 'smtp://XXXXXXX:6-2KklMXNG4prgdgdfgdgdfgo46ryaMCg#smtp.mandrillapp.com:587';
});
You can't set environment variables like that. You need to put it in your settings file, ie
{
"env": {
"MAIL_URL": "smtp://XXXXXXX:6-2KklMXNG4prgdgdfgdgdfgo46ryaMCg#smtp.mandrillapp.com:587"
}
}
and then when you run meteor
meteor --settings settings.json

Sequelize delete request with payload works with Postman but not with Vue Frontend implementation

I am trying to send PUT and DELETE requests with my express backend to a sqlite database. Put request works fine but DELETE request always fails.
I already checked the headers within the network tab, it seems to be the right one for both (application/json)
With postman, I can easily delete entries, but with my frontend the body does not seem to be set correctly.
const countryToPush = {title: countryName}
try{
await CountryService.post(countryToPush)
console.log(countryName + ' added!')
} catch(err)
{
console.log(err)
}
},
removeFromDb: async function(countryName){
const countryToDelete = {title: countryName}
try{
await CountryService.delete(countryToDelete)
console.log(countryName + ' deleted!')
} catch(err)
{
console.log(err)
}
}
This is within my vue file where I get the 'countryName' from an on click function.
try {
const country = await Country.create(req.body)
res.send(country)
} catch (err) {
res.status(500).send({
error: 'an error has occurred trying to create the country'
})
}
},
async delete (req, res) {
try {
const toDelete = await Country.findOne({
where: {
title: req.body.title
}
})
await toDelete.destroy()
res.send(req.body.title + ' was deleted')
} catch (err) {
res.status(500).send({
error: 'an error has occurred trying to delete the country'
})
}
}
Whereas this is the example from my sqlite calls
Unfortunately, the DELETE request from my vue frontend always fails and gives me the defined error 500 an error has occurred trying to delete the country.
Any ideas what else I could try to get it working?
Model.delete() is not a Sequelize function, you want to use Model.destroy().
await CountryService.destroy(countryToDelete)
Right now you are swallowing the actual error - add console.log(err) to your catch to see that it is probably saying CountryService.destroy is undefined.

Nativescript. nativescript-local-notifications always creates two notifications

I use nativescript-local-notifications and nativescript-plugin-firebase.
I want to create notification each time, when server send me a message. Here is code:
firebase.init({
storageBucket: 'gs://shao-by-partner-firebase.appspot.com',
persist: true, // optional, default false
onPushTokenReceivedCallback: function (token) {
Config.device_token = token;
console.log("Firebase plugin received a push token: " + token);
},
onMessageReceivedCallback: function (message) {
LocalNotifications.schedule([{
id: 1,
title: 'The title',
body: 'Recurs every minute until cancelled',
ticker: 'The ticker',
badge: 1,
smallIcon: 'res://heart.png'
}]).then(
function() {
console.log("Notification scheduled");
},
function(error) {
console.log("scheduling error: " + error);
}
)
}
}).then(
function (result) {
console.log("Firebase is ready");
},
function (error) {
console.log("firebase.init error: " + error);
}
);
}
But always created two notifications instead of one. And first notification is empty. And second notification is that I created. What's wrong?
I could be wrong here, but you are using two plugins to handle remote notifications?
nativescript-plugin-firebase already handles notifications for you, I don't think you need the local notifications plugin.
In the example you posted, you are receiving the original notification (the blank one), pluss the local one that you create in the onMessageReceivedCallback.
https://github.com/EddyVerbruggen/nativescript-plugin-firebase/blob/master/docs/MESSAGING.md#handling-a-notification
The is nothing in your onMessageReceived to determine if the message had any content.
You can try adding a conditional statement to your onMessageReceived function and check if the message has content. eg
if (message.title){
//send local notification
}
I found solution. Each time, when I create LocalNotification, I delete notification with id 0:
LocalNotifications.cancel (0);
But I still don't know,where it comes from.

'end' undefined for this.response in Iron Router for Meteor

I have created an HTTP POST endpoint for my Meteor server using Iron Router. I would like to send a response back to the requestor with a JSON of the status and some other metadata.
Here is the code for the endpoint:
Router.route('/new_video', {where: 'server'})
.post(function(){
var body = this.request.body;
this.response.setHeader('Content-Type', 'application/json');
var filename = body.filename;
console.log('New video uploaded for: ' + filename);
Meteor.call('newUpload', filename, function(error, results){
if (error){
throw new Meteor.Error("new-video-upload-failed", "New video could not be uploaded.");
var message = {
url: '/new_video',
status: 'success'
};
}
else{
var videoId = results;
console.log('Returned video id: ' + videoId);
var message = {
url: '/new_video',
status: 'failure'
};
}
this.response.end(JSON.stringify(message));
});
});
The Meteor console is printing:
=> Meteor server restarted
I20151002-15:51:26.311(-4)? New recording for: 1422776235,43.46756387,-80.54130886.mp4
I20151002-15:51:26.515(-4)? Returned video id: QiHXxZSb2sn9aNRPs
I20151002-15:51:26.569(-4)? Exception in delivering result of invoking 'newRecording': TypeError: Cannot call method 'end' of undefined
I20151002-15:51:26.569(-4)? at shared/routes.js:79:17
It's a common pitfall of JS where the value of this is modified due to the introduction of another function callback in the Meteor.call.
If you're using Meteor 1.2 which comes with ES2015 arrow functions you can solve the issue using this function declaration syntax instead :
Meteor.call('newUpload', filename, (error, results) => {
// here 'this' will keep referencing the POST route context
// so you can safely use this.response
});
If you're not using Meteor 1.2, use this syntax instead :
Meteor.call('newUpload', filename, function(error, results) {
// inner function is bound to parent function 'this'
}.bind(this));

How to turn non-idiomatc nodejs callback into thunk?

I'm using the Firebase node module and trying to convert it's callbacks to thunks to be able to use them in Koa.
This is the original event listener callback as per the Firebase documentation:
projects.on('value', function (snapshot) {
console.log('The read succeeded: ' + snapshot.val());
}, function (errorObject) {
console.log('The read failed: ' + errorObject.code);
});
And this is the where I want to add it in my Koa project:
function *list() {
// Get the data here and set it to the projects var
this.body = yield render('list', { projects: projects });
}
Anyone know how to to do it? Have tried thunkify, thunker and thu without success...
I don't think you can use thunkify etc because they are trying to convert a standard node function to a thunk. The firebase api doesn't follow the standard node.js callback signature of
fn(param1, parm2,.., function(err, result){});
which thunkify is expecting.
I think this would do it
var findProjectsByValue = function(value){
return function(callback){
projects.on(value, function(result){
callback(null, result);
}, function(err){
callback(err);
})
}
};
then you would consume it
var projects = yield findProjectsByValue('value');
Or you could just do rest api calls, which I assume is what you want. The firebase api seems to be more for evented scenarios, socketio etc

Resources