Created
February 5, 2019 19:21
-
-
Save ashatat/aa62bbcb0291da8dca75329af07c3240 to your computer and use it in GitHub Desktop.
upload media files on twitter api, not working with all videos :(
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const client = new Twitter({ | |
consumer_key: process.env.TWITTER_CONSUMER_KEY, | |
consumer_secret: process.env.TWITTER_CONSUMER_SECRET, | |
access_token_key: process.env.oauthAccessToken, | |
access_token_secret: process.env.oauthAccessSecret, | |
}); | |
// after uploading the file and store it on the server using multer the path will be in (file.path) | |
const streamFile = fs.createReadStream(file.path, { highWaterMark: 128 * 1024 }); | |
function makePost(endpoint, params, counter) { | |
return new Promise((resolve, reject) => { | |
client.post(endpoint, params, (error, data, response) => { | |
if (error) { | |
console.log(counter, 'error make post', error); | |
reject(error); | |
} else { | |
resolve(data); | |
} | |
}); | |
}); | |
} | |
makePost('media/upload', { | |
command: 'INIT', | |
total_bytes: file.size, | |
media_type: file.mimetype, | |
}, 'init') | |
.then((data) => { | |
let counter = 0; | |
const asyncArr = []; | |
streamFile.on('data', (chunk) => { | |
asyncArr.push(makePost('media/upload', { | |
command: 'APPEND', | |
media_id: data.media_id_string, | |
media: chunk, | |
segment_index: counter, | |
}, counter)); | |
counter += 1; | |
}); | |
streamFile.on('end', () => { | |
Promise.all(asyncArr) | |
.then(() => { | |
makePost('media/upload', { | |
command: 'FINALIZE', | |
media_id: data.media_id_string, | |
}) | |
.then(result => console.log(result)).catch(error => console.log(error)); | |
}) | |
.catch(console.log); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment