coreHandler.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. 'use strict';
  2. // nodejs modules
  3. const path = require('path'),
  4. fs = require('fs'),
  5. os = require('os'),
  6. events = require('events');
  7. // npm modules
  8. const config = require('config'),
  9. request = require('request'),
  10. waterfall = require('async/waterfall'),
  11. passport = require('passport');
  12. // custom modules
  13. const global = require('./global'),
  14. stations = require('./stations');
  15. var eventEmitter = new events.EventEmitter();
  16. module.exports = {
  17. // module functions
  18. on: (name, cb) => {
  19. eventEmitter.on(name, cb);
  20. },
  21. emit: (name, data) => {
  22. eventEmitter.emit(name, data);
  23. },
  24. // core route handlers
  25. '/users/login': (user, cb) => {
  26. passport.authenticate('local-login', {
  27. // successRedirect: cb({ status: 'success', message: 'Successfully logged in' }),
  28. // failureRedirect: cb({ status: 'error', message: 'Error while trying to log in' })
  29. });
  30. },
  31. '/users/register': (user, cb) => {
  32. console.log(user);
  33. passport.authenticate('local-signup');
  34. },
  35. '/stations': cb => {
  36. cb(stations.getStations().map(function (result) {
  37. return {
  38. id: result.getId(),
  39. displayName: result.getDisplayName(),
  40. description: result.getDescription(),
  41. users: result.getUsers()
  42. }
  43. }));
  44. },
  45. '/stations/join/:id': (id, user, cb) => {
  46. const station = stations.getStation(id);
  47. if (station) {
  48. user.stationId = id;
  49. this.emit('station-joined', {
  50. user: {
  51. id: user.id,
  52. username: user.username
  53. }
  54. });
  55. return cb({
  56. status: 'joined',
  57. data: {
  58. displayName: station.getDisplayName(),
  59. users: station.getUsers(),
  60. currentSong: station.getCurrentSong()
  61. }
  62. });
  63. }
  64. else {
  65. return cb({ status: 'error', message: 'Room with that ID does not exists' });
  66. }
  67. },
  68. '/stations/search/:query': (query, cb) => {
  69. const params = [
  70. 'part=snippet',
  71. `q=${encodeURIComponent(query)}`,
  72. `key=${config.get('apis.youtube.key')}`,
  73. 'type=video',
  74. 'maxResults=25'
  75. ].join('&');
  76. request(`https://www.googleapis.com/youtube/v3/search?${params}`, (err, res, body) => {
  77. if (err) {
  78. return cb({ status: 'error', message: 'Failed to make request' });
  79. }
  80. else {
  81. try {
  82. return cb({ status: 'success', body: JSON.parse(body) });
  83. }
  84. catch (e) {
  85. return cb({ status: 'error', message: 'Non JSON response' });
  86. }
  87. }
  88. });
  89. }
  90. };