Guest User

Untitled

a guest
Dec 16th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. // app.js
  2. const WebSocket = require('ws');
  3. var fs = require('fs');
  4. var youtubedl = require('youtube-dl');
  5. var crypto = require('crypto');
  6. var qs = require('qs');
  7. var request = require('request');
  8. var server = 'wss://my.webhookrelay.com/v1/socket';
  9. var reconnectInterval = 1000 * 3;
  10. var ws;
  11. var apiKey = process.env.RELAY_KEY;
  12. var apiSecret = process.env.RELAY_SECRET;
  13. var connect = function () {
  14. ws = new WebSocket(server);
  15. ws.on('open', function () {
  16. console.log('Connected, sending authentication request');
  17. ws.send(JSON.stringify({ action: 'auth', key: apiKey, secret: apiSecret }));
  18. });
  19. ws.on('message', function incoming(data) {
  20. var msg = JSON.parse(data);
  21. if (msg.type === 'status' && msg.status === 'authenticated') {
  22. console.log('Authenticated, subscribing to the bucket...')
  23. ws.send(JSON.stringify({ action: 'subscribe', buckets: ['slash'] }));
  24. return
  25. }
  26. if (msg.type === 'webhook') {
  27. processWebhook(qs.parse(msg.body))
  28. }
  29. });
  30. ws.on('error', function () {
  31. console.log('socket error');
  32. });
  33. ws.on('close', function () {
  34. console.log('socket closed, reconnecting');
  35. setTimeout(connect, reconnectInterval);
  36. });
  37. };
  38. var processWebhook = function (payload) {
  39. console.log('URL: ', payload.text)
  40. var tempFilename = 'tmp-' + crypto.randomBytes(4).readUInt32LE(0);
  41. var actualFilename = ''
  42. var video = youtubedl(payload.text,
  43. ['--format=18'],
  44. { cwd: __dirname });
  45. // Will be called when the download starts.
  46. video.on('info', function (info) {
  47. console.log('Download started');
  48. console.log('Filename: ' + info._filename);
  49. // saving filename for the later rename
  50. actualFilename = info._filename;
  51. console.log('Size: ' + info.size);
  52. });
  53. video.pipe(fs.createWriteStream(tempFilename));
  54. video.on('end', function () {
  55. console.log('Finished downloading!');
  56. // renaming file to the actual video name from our temp one
  57. if (actualFilename !== '') {
  58. fs.rename(tempFilename, actualFilename, function (err) {
  59. if (err) console.log('ERROR: ' + err);
  60. });
  61. }
  62. // sending response back to Slack
  63. respond(payload, {
  64. response_type: 'in_channel',
  65. text: `${actualFilename} finished downloading!`
  66. })
  67. });
  68. }
  69. var respond = function (payload, result) {
  70. request.post(
  71. payload.response_url,
  72. { json: result },
  73. function (error, response, body) {
  74. if (!error && response.statusCode == 200) {
  75. console.log(body)
  76. return
  77. }
  78. console.log(error)
  79. }
  80. );
  81. }
  82. connect();
Add Comment
Please, Sign In to add comment