Skip to content

Instantly share code, notes, and snippets.

@joelmarquez90
Created September 15, 2017 20:56
Show Gist options
  • Save joelmarquez90/02111df715d8ca8ad7586637b705c5e6 to your computer and use it in GitHub Desktop.
Save joelmarquez90/02111df715d8ca8ad7586637b705c5e6 to your computer and use it in GitHub Desktop.
Upload Twitter Video using its API
// Retrieve user access token someway, get the twitter text and pass the file in req.file
var doPublishVideoTweet = function(access_token, text, file) {
var stats = fs.statSync(file.path);
var formData = {
command: 'INIT',
media_type: file.mimetype,
total_bytes: stats.size
};
// First step, we send the size of the video
request.post({ url: twitterUtils.getUserUploadMediaURL(), oauth: twitterUtils.getOauthParam(access_token),
form: formData, json: true }, function(err, response, body) {
if (!err) {
// With its response, start transfering the video
transferProcess(0, body.media_id_string, file, stats.size, access_token, function(err) {
if (!err) {
var formData = {
command: 'FINALIZE',
media_id: body.media_id_string
};
// Once the transfer is done, we publish the video
request.post({ url: twitterUtils.getUserUploadMediaURL(), oauth: twitterUtils.getOauthParam(access_token),
form: formData, json: true }, function(err, response, body) {
if (!err && !body.error) {
doPublishTweet(access_token, text, body.media_id_string, null);
}
});
}
});
}
});
};
// Transfers each part of the video until the end
var transferProcess = function(index, mediaId, file, fileSize, access_token, callback) {
// We open the file
var fd = fs.openSync(file.path, 'r');
var bytesRead, data, bufferLength = 268435456;
var buffer = new Buffer(1000000000);
var startOffset = index * bufferLength;
var length = startOffset + bufferLength > fileSize ? fileSize - startOffset : bufferLength;
// We read the amount of bytes specified in startOffset until length
bytesRead = fs.readSync(fd, buffer, startOffset, length, null);
// This boolean tells us that the last part is being transferred
var completed = bytesRead < bufferLength;
data = completed ? buffer.slice(0, bytesRead) : buffer;
// We generate a chunk file with the readed data
var chunkFileName = copyFileName + '-chunked-' + index;
// And save that file so we can read it and send it
fs.writeFile(chunkFileName, data, function(err) {
if (err) {
callback(err);
}
else {
var formData = {
command: 'APPEND',
media_id: mediaId,
segment_index: index
};
formData.media = fs.createReadStream(chunkFileName);
var oauth = {
consumer_key: 'TWITTER_KEY',
consumer_secret: 'TWITTER_SECRET',
token: access_token.token,
token_secret: access_token.token_secret
};
// Once the file has been written, we upload it
request.post({ url: 'https://upload.twitter.com/1.1/media/upload.json', oauth: oauth,
formData: formData, json: true }, function (err, response) {
if (err) {
callback(err);
}
else if (completed) {
callback(null);
}
// We keep uploading increasing the index until the end
else {
transferProcess(index + 1, mediaId, file, fileSize, access_token, callback);
}
});
}
});
};
// Finally we publish the Tweet with the associated mediaId
var doPublishTweet = function(access_token, text, mediaId, callback) {
var qs = {};
if (text) {
qs.status = text;
}
if (mediaId) {
qs.media_ids = mediaId;
}
var url = twitterUtils.getUserPublishContentURL();
var oauth = {
consumer_key: 'TWITTER_KEY',
consumer_secret: 'TWITTER_SECRET',
token: access_token.token,
token_secret: access_token.token_secret
};
request.post({ url: 'https://api.twitter.com/1.1/statuses/update.json', oauth: oauth, qs: qs, json: true }, function(err, response) {
callback(null);
});
};
// Import multer library
var multer = require('multer');
// Craete an upload object
var upload = multer({ limits: { fileSize: 50 * 1024 * 1024 }, storage: multer.diskStorage({}) });
// In an Express router, add the upload object as a middleware
userRoutes.post('/:user_id/media', upload.single('file'), twitterController.publishVideo);
@mvrozanti
Copy link

Why does one need to use 'multer'?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment