Mailgun - Attach a file in phantomjs - phantomjs

I am trying to make a application using phantomjs which requires mailgun service to send email. Since there is no official mailgun phantomjs library, I am facing some troubles with attaching files in the emails. The email is dispatched successfully but I dont see any attachment to it.
Here is the code:
function ObjToQs(obj) {
var str = "";
for (key in obj) {
str += key + '=' + obj[key] + '&';
}
str = str.slice(0, str.length - 1);
return str;
}=
var page = require('webpage').create(),
url = 'https://api.mailgun.net/v3/sandboxbxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.org/messages',
data = {
from: "Ganesh <mail#gmail.com>",
to: "email#gmail.com",
subject: "subject!",
text: "Body",
attachment: '/path/test.txt'
};
console.log(ObjToQs(data));
page.customHeaders = {'Authorization': 'Basic ' + btoa('api:key-xxxxxxxx')};
page.open(url, 'post', ObjToQs(data), function (status) {
if (status !== 'success') {
console.log('FAIL to load the log');
console.log(status);
} else {
console.log('Log success');
var result = page.evaluate(function () {
return document.body.innerText;
});
console.log("log Result: " + result);
phantom.exit();
}
});
What should I do?
Thanks!

This will work for you -- it's a NodeJS lib for mailgun: https://www.npmjs.com/package/mailgun-js

Related

Loading webpage incompletely Phantomjs

I have problems capturing and loading the webpage:
https://myaccount.nytimes.com/auth/login
The username and password fields as well as the submit button are missing. What could be the reason? Thanks
As you can see the code listed below waits for each and all the resources to be loaded, one by one.
I did not write the code, however it is excellent and tested by many. The original can be found here:
https://gist.github.com/cjoudrey/1341747
(ALL the credits to the guy who wrote it.)
var resourceWait = 3000,
maxRenderWait = 30000,
url = 'https://myaccount.nytimes.com/auth/login'; //'https://twitter.com/#!/nodejs';
var page = require('webpage').create(),
count = 0,
forcedRenderTimeout,
renderTimeout;
page.viewportSize = { width: 1280, height : 1024 };
function doRender() {
page.render('twitter.png');
phantom.exit();
}
page.onResourceRequested = function (req) {
count += 1;
console.log('> ' + req.id + ' - ' + req.url);
clearTimeout(renderTimeout);
};
page.onResourceReceived = function (res) {
if (!res.stage || res.stage === 'end') {
count -= 1;
console.log(res.id + ' ' + res.status + ' - ' + res.url);
if (count === 0) {
renderTimeout = setTimeout(doRender, resourceWait);
}
}
};
page.open(url, function (status) {
if (status !== "success") {
console.log('Unable to load url');
phantom.exit();
} else {
forcedRenderTimeout = setTimeout(function () {
console.log(count);
doRender();
}, maxRenderWait);
}
});

Angular 5 HttpRequest reportProgress

I have a block of code that when executed in every other browser including IE11 works just fine, but for whatever reason when Edge runs this code I don't get a progress like the other browsers.
Edge logs this:
progress-- true
event.type == 0
A long pause and then writes:
progress: true
loaded: xxx
total: xxx
type: 1
Code:
Upload(file : File, id:number, endPoint:string) : void {
const formData = new FormData();
formData.append(file.name, file);
var auth = "Bearer " + this.Auth.GetAuth();
var autoThumb = this.stagedThumb == null ? 'true' : 'false';
const uploadRequest = new HttpRequest('POST', endPoint + `?id=${id}&thumb=${autoThumb}`, formData, {
reportProgress: true,
headers: new HttpHeaders({
'Authorization': auth
})
});
this.PerformUpload(uploadRequest);
}
PerformUpload(uploadRequest : HttpRequest<FormData>, progress: boolean = true) : void {
this.http.request(uploadRequest).subscribe(event =>
{
console.log("Http Event Message -- Progress: " + progress);
console.log(event);
console.log("End Event Message");
if (progress)
{
if (event.type == HttpEventType.UploadProgress)
{
this.progress = Math.round(100 * event.loaded / event.total);
}
else if (event.type == HttpEventType.Response)
{
this.message = event.body.toString();
setTimeout(() => {
this.ResetForm();
}, 2*1000);
}
}
});
}
In case you have not found the root cause yet, it seems this is an open issue for MS Edge.
See https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12224510/

Sharp image uploader not working when running app with PM2

I have an express app that I am using Sharp to resize images after a user has uploaded them. When I start the app using 'npm start' I am able to upload the images with no issues, but if I use PM2 to manage the process the images don't get saved on the server. I can save them without using Sharp to resize them, it is only when I have the code for sharp that they don't get saved. Below is the code from my controller. Multer is processing the form and sharp is resizing the image.
doNewRecipe: function(req, res) {
for (var key in req.body) {
req.body[key] = req.body[key] || undefined;
}
var body = _.pick(req.body, 'title', 'description', 'ingredients', 'instructions', 'yield', 'prep_time', 'cook_time', 'categoryId');
body.userId = req.session.user.id;
if (req.file) {
var tempPath = req.file.path,
ext = path.extname(req.file.originalname).toLowerCase(),
//targetPath = path.resolve(finalUploadPath + req.file.filename + ext);
targetPath = path.resolve(finalUploadPath);
fs.renameSync(tempPath, tempPath + ext);
var newFileName = req.file.filename + ext;
var imageFile = tempPath + ext;
body.image = newFileName;
sharp(imageFile)
.resize(450, 450)
.max()
.toFile('./public/finalUpload/' + newFileName, function(err, info) {
body.image = newFileName;
fs.unlinkSync(path.resolve(tempPath + ext));
db.recipe.create(body).then(function(recipe) {
res.redirect('/recipe/view/' + recipe.id);
}, function(e) {
console.log(e.message);
res.render('error', {message: e.toString()});
});
});
//fs.renameSync(tempPath, targetPath);
} else {
db.recipe.create(body).then(function(recipe) {
res.redirect('/recipe/view/' + recipe.id);
}, function(e) {
console.log(e.message);
res.render('error', {message: e.toString()});
});
}
},
If you use path to determine where to save the file it will transport easily from one system to another. I actually created a few variables to determine where to save the file. Below is my code.
if (process.env.NODE_ENV === 'production') {
var finalUploadPath = 'hidden';
var googleTracking = true;
} else if (process.env.NODE_ENV === 'staging') {
var finalUploadPath = 'hidden';
var googleTracking = false;
} else {
var finalUploadPath = 'hidden';
var googleTracking = false;
}
sharp(imageFile)
.resize(450, 450)
.max()
.toFile(finalUploadPath + req.file.filename + '.jpg', function(err, info) {
body.image = req.file.filename + '.jpg';
fs.unlinkSync(path.resolve(tempPath + ext));
compressAndResize(path.resolve(__dirname, '../public/finalUpload/' + body.image));
db.recipe.create(body).then(function(recipe) {
req.flash('success', 'Recipe created');
res.redirect('/recipe/view/' + recipe.id + '/' + recipe.slug);
}, function(e) {
console.log(e.message);
req.flash('error', 'Error creating new recipe');
res.render('error', {message: e.toString(), csrfToken: req.csrfToken(), google: googleTracking});
});
});

Express Deprecated

I have a photo app that uploads photos to AWS. When testing the uploading photos feature on my localhost, my terminal throws the following error:
express deprecated res.send(status, body): Use
res.status(status).send(body) instead aws/aws.js:50:18
My photos DO save to AWS, im just wondering what this error is and how to fix it. Below is my aws code that the error refers too.
'use strict';
var AWS = require('aws-sdk'),
crypto = require('crypto'),
config = require('./aws.json'),
createS3Policy,
getExpiryTime;
getExpiryTime = function () {
var _date = new Date();
return '' + (_date.getFullYear()) + '-' + (_date.getMonth() + 1) + '-' +
(_date.getDate() + 1) + 'T' + (_date.getHours() + 3) + ':' + '00:00.000Z';
};
createS3Policy = function(contentType, callback) {
var date = new Date();
var s3Policy = {
'expiration': getExpiryTime(),
'conditions': [
['starts-with', '$key', 'images/'],
{'bucket': config.bucket},
{'acl': 'public-read'},
['starts-with', '$Content-Type', contentType],
{'success_action_status' : '201'}
]
};
// stringify and encode the policy
var stringPolicy = JSON.stringify(s3Policy);
var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64');
// sign the base64 encoded policy
var signature = crypto.createHmac('sha1', config.secretAccessKey)
.update(new Buffer(base64Policy, 'utf-8')).digest('base64');
// build the results object
var s3Credentials = {
s3Policy: base64Policy,
s3Signature: signature,
AWSAccessKeyId: config.accessKeyId
};
// send it back
callback(s3Credentials);
};
exports.getS3Policy = function(req, res) {
createS3Policy(req.query.mimeType, function (creds, err) {
if (!err) {
return res.send(200, creds);
} else {
return res.send(500, err);
}
});
};
Replace res.send(statusCode, "something") with res.status(statusCode).send("something")
This should do it for your code:
exports.getS3Policy = function(req, res) {
createS3Policy(req.query.mimeType, function (creds, err) {
if (!err) {
return res.send(creds); //200 is not needed here, express will default to this
} else {
return res.status(500).send(err);
}
});
};

Can I get the failed request id when PhantomJS get resource error?

I don't quite understand why PhantomJS only returns the url of request for onResourceError callback, while for the other two resource callbacks it returns the request id. That makes "finding which request did actually fail" really impossible if there is more than one request to the same url. Does anyone knows how to get the failed request id?
Actually, that's just old documentation. onResourceError has the id of a failed request.
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (request ID:' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
Why do you really need to request id ?
Since onResourceError was added in 1.9, some information may be missing.
A way to resolve your problem is to keep in an array all requested resourcessuach as in netsniff example.
Here is a very basic implementation :
var page = require('webpage').create(),
system = require('system');
if (system.args.length === 1) {
console.log('Usage: netsniff.js <some URL>');
phantom.exit(1);
} else {
page.address = system.args[1];
page.resources = [];
page.onLoadStarted = function () {
page.startTime = new Date();
};
page.onResourceRequested = function (req) {
page.resources[req.id] = {
request: req,
startReply: null,
endReply: null
};
};
page.onResourceReceived = function (res) {
if (res.stage === 'start') {
page.resources[res.id].startReply = res;
}
if (res.stage === 'end') {
page.resources[res.id].endReply = res;
}
};
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
page.resources.forEach(function (resource) {
var request = resource.request,
endReply = resource.endReply;
if (request && request.url === resourceError.url && !endReply) {
console.log('request id was :' + request.id);
}
})
};
page.open(page.address, function (status) {
var har;
if (status !== 'success') {
console.log('FAIL to load the address');
phantom.exit(1);
} else {
page.endTime = new Date();
page.title = page.evaluate(function () {
return document.title;
});
console.log(page.title);
phantom.exit();
}
});
}
onResourceError, you just need to find first/last/all recorded urls that match the error resource url.