Post image on twitter using puppeteer - node.js

Is it possible to post an image on twitter using nodejs and puppeteer? It find it hard because when you click on the image button on twitter it opens your archive.

It's definetely possible to post image on Twitter automatically (using Node.js). Twitter API Client for node called 'twit' suits for it. You can find the package on github or npm.
// post a tweet with media
var b64content = fs.readFileSync('/path/to/img', { encoding: 'base64' })
// first we must post the media to Twitter
T.post('media/upload', { media_data: b64content }, function (err, data, response) {
// now we can assign alt text to the media, for use by screen readers and
// other text-based presentations and interpreters
var mediaIdStr = data.media_id_string
var altText = "Small flowers in a planter on a sunny balcony, blossoming."
var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }
T.post('media/metadata/create', meta_params, function (err, data, response) {
if (!err) {
// now we can reference the media and post a tweet (media will attach to the tweet)
var params = { status: 'loving life #nofilter', media_ids: [mediaIdStr] }
T.post('statuses/update', params, function (err, data, response) {
console.log(data)
})
}
})
})
// post media via the chunked media upload API.
// You can then use POST statuses/update to post a tweet with the media attached as in the example above using `media_id_string`.
// Note: You can also do this yourself manually using T.post() calls if you want more fine-grained
// control over the streaming. Example: https://github.com/ttezel/twit/blob/master/tests/rest_chunked_upload.js#L20
//
var filePath = '/absolute/path/to/file.mp4'
T.postMediaChunked({ file_path: filePath }, function (err, data, response) {
console.log(data)
})

Related

Unable to send photo using Form Submit

I've a photo and a paid upload service : http://example.com/in.php .
I'm not able to upload a given jpeg file using this code. It is telling me that invalid file format uploaded. But using file linux command I can see it is JPEG format. Is there any problem in this code?
fs.readFile('/tmp/photo.jpg'', 'utf8', function(err, contents) {
var b64 = new Buffer(contents);
var s = b64.toString('base64');
var request = require('request')
request.post('http://example.com/in.php', {
form: {
method:'base64',
key:'cplbhvnmvdn4bjxxchzgqyjz7rf9fy8w',
body:s,
}
}, function (err, res, body) {
console.log("body=",body);
console.log("res=",res);
})
});
I see no mistakes in your process of converting jpeg to base64. However, I would suggest a workaround to use a small image-to-base64 node package.
Also, there's a higher chance of something being wrong in the post request, maybe the upload service API is not accepting the base64 format, maybe the API key is not authorized. Please read their API docs carefully and do as it says & also console log the error code you are receiving.
After all, try something like this with Axios.
const image2base64 = require('image-to-base64');
image2base64("path/to/file.jpg") // you can also to use url
.then(
(response) => {
console.log(response); //cGF0aC90by9maWxlLmpwZw==
axios.post('http://example.com/in.php', base64, {
headers: {
"Content-Type": "multipart/form-data"
},
}).then((response) => {
console.log(response)
}).catch(function (error) {
console.log("Error in uploading.");
});
},
}
)
.catch(
(error) => {
console.log(error); //Exepection error....
}
)

How to save form data that include image using nodejs posted using angular 2

I am creating a application using mean stack, in which i am using angular 2 for the client side. I had created a form that contain some input fields and a image. Now, for submitting the form i am using formdata to send data to the node server. now I am unable to show, access and save the data at the node server. Please somebody help me as I am new to mean stack.
data array:
const newProduct = {
category: this.pcategory,
name: this.name,
description: this.description,
price: this.price,
quantity: this.quantity,
image: this.fileName
}
here is the code for sending data:
imagedata contain the data of the file
addProduct(newProduct, imagedata:File) {
let formData: FormData = new FormData();
formData.append('body', JSON.stringify(newProduct));
formData.append('file', image, newProduct.imagedata);
let headers = new Headers();
headers.append("enctype", "multipart/form-data");
headers.append("Accept", "application/json");
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:3000/product/add' ,formData, options).map((response: Response) => response.json());
}
here is the code for receiving and saving data:
function (req, res) {
var storage = multer.diskStorage({//multers disk storage settings
destination: function (req, file, callback) {
callback(null, './uploads');
}
});
var upload = multer({//multer settings
storage: storage
}).any();
var model = new Model(req.body);
model.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.status(201).json(model);
}
});
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
console.log(err);
return res.status(422).send("an Error occured")
}
});
}
In angular 2 you cannot upload image with this approach consider using this Angular 2 module ng2-file-uploader. You can see the demo app here Angular File Uploads with an Express Backend
.
One solution could be to convert your image to base64 string and pass that string in your model. And then have that base64 string convert back to image in the server.

How efficiently post a tweet with a remote image with Nodejs Stream?

I need to download a remote image, that its path is saved on the wineTweet.label attribut.
And then POST a tweet with this image.
My implementation is working, but I first save the image to a file and then read it before posting it.
Here is the code :
var file = fs.createWriteStream("file.jpg");
https.get(wineTweet.label, function (response) {
response.pipe(file);
file.on('finish', function () {
var data = require('fs').readFileSync('file.jpg');
// Make post request on media endpoint. Pass file data as media parameter
client.post('media/upload', {media: data}, function (error, media, response) {
if (!error) {
// If successful, a media object will be returned. // Lets tweet it
var status = {
status : 'I am a tweet',
media_ids: media.media_id_string // Pass the media id string
}
client.post('statuses/update', status, function (error, tweet, response) {
if (!error) {
console.log(tweet);
});
}
});
});
});
How to directly connect ReadingStream to the POST request ?
Just use the response directly, which is already a Readable stream, instead of writing/reading a temporary file:
https.get(wineTweet.label, function(res) {
// Make post request on media endpoint. Pass file data as media parameter
client.post('media/upload', {media: res}, function(error, media, response) {
if (!error) {
// If successful, a media object will be returned. // Lets tweet it
var status = {
status : 'I am a tweet',
media_ids: media.media_id_string // Pass the media id string
};
client.post('statuses/update', status, function(error, tweet, response) {
if (!error)
console.log(tweet);
});
}
});
});
On an unrelated note, you should handle errors appropriately instead of ignoring them.

how to receive and process a photo mms using twilio

Looking for an example, of how to receive and process images via mms to my app using Twilio.
Looking at the number configuration screen in the twilio dashboard, I assume that I set up an incoming phone number and a HTTP POST url to send incoming mms to. However, I'm not sure what gets posted to that url and don't know the structure of that data.
Does someone have an example of what data gets POSTed to the url and in what format? Any javascript examples of what data the server would process would be great.
Firstly use the twilio-node module(npm install twilio). Once you have that in place, you can just access the webhook request body like you would any request body req.body.
As depicted in twilio's docs, the structure is like so:
{
MessageSid: String, //ID pertaining to this message
AccountSid: String, //ID pertaining to your twilio account
From: String, //phone number of sender
To: String, //recipients phone number, you in this case
Body: String, //Message body
NumMedia: Number, //number of attached media
//these values only appear when media is present(NumMedia.length > 0)
MediaContentType: [String] //type of content in SMS
MediaUrl: [String] //URL to download the media
}
You can then do something like this using the twilio modules, caolan/async module, and the popular request/request module:
var twilio = require('twilio'),
fs = require('fs'),
async = require('async'),
request = require('request');
app.post('/mms', function(req, res) {
var options = { url: 'https://subtle-gradient-188.herokuapp.com/twiml' };
if (!twilio.validateExpressrequire(req, 'YOUR_TWILIO_AUTH_TOKEN', options)) return res.status(401).send("Bad key!");
if(!req.body.hasOwnProperty('MediaUrl')) return res.send("Missing media...");
var media = req.body.MediaUrl;
//download all media
async.map(media, download, function(err, filenames) {
var resp = new twilio.TwimlResponse();
if(err) {
resp.say("Problem occured");
console.log(err);
}
else resp.say('Files recieved: ' + filenames.join(', '));
res.type('text/xml');
res.send(resp.toString());
});
});
//download a single url to a unique filename
function download(url, cb) {
var name = Date.now() + url.split('/').pop();
request
.get(url)
.on('error', cb)
.on('end', function() {
cb(null, name);
})
.pipe(fs.createWriteStream(name));
}

mongodb gridfs encoding picture base64

i try to readout an image, saved in mongodb, via gridfs (without temporary file)
it should be directly sent to ajax, which injects it into html
when i use my actual functions a large bit string is formed and sent to client (is saved in ajax response var)
but as it reaches the client, the bits arent correct anymore
so i look for a way to encode the picture before it is sent (into base64)
(or is there any other way?)
Serverside - javascript, gridfs
exports.readFileFromDB = function(req, res, profile, filename, callback){
console.log('Find data from Profile ' + JSON.stringify(profile));
var GridReader = new GridStore(db, filename,"r");
GridReader.open(function(err, gs) {
var streamFile = gs.stream(true);
streamFile.on("end", function(){
});
// Pipe out the data
streamFile.pipe(res);
GridReader.close(function(err, result) {
});
Clientside - javascript ajax call:
function imgUpload(){
var thumb = $("#previewPic");
$('#uploadForm').ajaxSubmit({
beforeSend:function(){
//launchpreloader();
},
error: function(xhr) {
//status('Error: ' + xhr.status);
},
success: function(response) {
console.log(response);
var imageData = $.base64Encode(response);
console.log(imageData);
thumb.attr("src","data:image/png;base64"+imageData);
$("#spanFileName").html("File Uploaded")
}
});
}
I'm doing something similar for a current project, but when the upload is complete, I return a JSON object containing the URL for the uploaded image:
{ success : true, url : '/uploads/GRIDFSID/filename.ext' }
I have a route in Express that handles the /uploads route to retrieve the file from GridFS and stream it back to the client, so I can use the above URL in an IMG SRC. This is effectively what appears in the DOM:
<img src="/uploads/GRIDFSID/filename.ext">
The route handler looks something like this (it uses node-mime and gridfs-stream):
app.get(/^\/uploads\/([a-f0-9]+)\/(.*)$/, function(req, res) {
var id = req.params[0];
var filename = req.params[1];
// Set correct content type.
res.set('Content-type', mime.lookup(filename));
// Find GridFS file by id and pipe it to the response stream.
gridfs
.createReadStream({ _id : id })
.on('error', function(err) {
res.send(404); // or 500
})
.pipe(res);
});
It obviously depends on your exact setup if my solution works for you.

Resources