coreHandler.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. bcrypt = require('bcrypt'),
  12. passport = require('passport');
  13. // custom modules
  14. const global = require('./global'),
  15. stations = require('./stations');
  16. var eventEmitter = new events.EventEmitter();
  17. const edmStation = new stations.Station("edm", {
  18. "genres": ["edm"],
  19. playlist: [
  20. {
  21. id: "dQw4w9WgXcQ",
  22. title: "Never gonna give you up",
  23. artists: ["Rick Astley"],
  24. duration: 20,
  25. thumbnail: "https://yt3.ggpht.com/-CGlBu6kDEi8/AAAAAAAAAAI/AAAAAAAAAAA/Pi679mvyyyU/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
  26. likes: 0,
  27. dislikes: 1
  28. },
  29. {
  30. id: "GxBSyx85Kp8",
  31. title: "Yeah!",
  32. artists: ["Usher"],
  33. duration: 20,
  34. thumbnail: "https://yt3.ggpht.com/-CGlBu6kDEi8/AAAAAAAAAAI/AAAAAAAAAAA/Pi679mvyyyU/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
  35. likes: 0,
  36. dislikes: 1
  37. }
  38. ],
  39. currentSongIndex: 0,
  40. paused: false,
  41. displayName: "EDM",
  42. description: "EDM Music"
  43. });
  44. const popStation = new stations.Station("pop", {
  45. "genres": ["pop"],
  46. playlist: [
  47. {
  48. id: "HXeYRs_zR6w",
  49. title: "Nobody But Me",
  50. artists: ["Michael Bublé"],
  51. duration: 12,
  52. thumbnail: "https://yt3.ggpht.com/-CGlBu6kDEi8/AAAAAAAAAAI/AAAAAAAAAAA/Pi679mvyyyU/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
  53. likes: 0,
  54. dislikes: 1
  55. },
  56. {
  57. id: "CR4YE7htLgI",
  58. title: "Someday ",
  59. artists: ["Michael Bublé", "Meghan Trainor"],
  60. duration: 30,
  61. thumbnail: "https://yt3.ggpht.com/-CGlBu6kDEi8/AAAAAAAAAAI/AAAAAAAAAAA/Pi679mvyyyU/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
  62. likes: 0,
  63. dislikes: 1
  64. }
  65. ],
  66. currentSongIndex: 0,
  67. paused: false,
  68. displayName: "Pop",
  69. description: "Pop Music"
  70. });
  71. stations.addStation(edmStation);
  72. stations.addStation(popStation);
  73. module.exports = {
  74. // module functions
  75. on: (name, cb) => {
  76. eventEmitter.on(name, cb);
  77. },
  78. emit: (name, data) => {
  79. eventEmitter.emit(name, data);
  80. },
  81. // core route handlers
  82. '/users/register': (username, email, password, recaptcha, cb) => {
  83. console.log(username, password);
  84. request({
  85. url: 'https://www.google.com/recaptcha/api/siteverify',
  86. method: 'POST',
  87. form: {
  88. 'secret': config.get("apis.recapthca.secret"),
  89. 'response': recaptcha
  90. }
  91. }, function (error, response, body) {
  92. if (error === null && JSON.parse(body).success === true) {
  93. body = JSON.parse(body);
  94. global.db.user.findOne({'username': username}, function (err, user) {
  95. console.log(err, user);
  96. if (err) return cb(err);
  97. if (user) return cb("username");
  98. else {
  99. global.db.user.findOne({'email.address': email}, function (err, user) {
  100. console.log(err, user);
  101. if (err) return cb(err);
  102. if (user) return cb("email");
  103. else {
  104. // TODO: Email verification code, send email
  105. bcrypt.genSalt(10, function (err, salt) {
  106. if (err) {
  107. return cb(err);
  108. } else {
  109. bcrypt.hash(password, salt, function (err, hash) {
  110. if (err) {
  111. return cb(err);
  112. } else {
  113. let newUser = new global.db.user({
  114. username: username,
  115. email: {
  116. address: email,
  117. verificationToken: global.generateRandomString("64")
  118. },
  119. services: {
  120. password: {
  121. password: hash
  122. }
  123. }
  124. });
  125. newUser.save(function (err) {
  126. if (err) throw err;
  127. return cb(null, newUser);
  128. });
  129. }
  130. });
  131. }
  132. });
  133. }
  134. });
  135. }
  136. });
  137. } else {
  138. cb("Recaptcha failed");
  139. }
  140. });
  141. },
  142. '/stations': cb => {
  143. cb(stations.getStations().map(station => {
  144. return {
  145. id: station.id,
  146. playlist: station.playlist,
  147. displayName: station.displayName,
  148. description: station.description,
  149. currentSongIndex: station.currentSongIndex
  150. }
  151. }));
  152. },
  153. '/youtube/getVideo/:query': (query, cb) => {
  154. const params = [
  155. 'part=snippet',
  156. `q=${encodeURIComponent(query)}`,
  157. `key=${config.get('apis.youtube.key')}`,
  158. 'type=video',
  159. 'maxResults=15'
  160. ].join('&');
  161. // function params(type, id) {
  162. // if (type == "search") {
  163. // return [
  164. // 'part=snippet',
  165. // `q=${encodeURIComponent(query)}`,
  166. // `key=${config.get('apis.youtube.key')}`,
  167. // 'type=video',
  168. // 'maxResults=15'
  169. // ].join('&');
  170. // } else if (type == "video") {
  171. // return [
  172. // 'part=snippet,contentDetails,statistics,status',
  173. // `id=${encodeURIComponent(id)}`,
  174. // `key=${config.get('apis.youtube.key')}`
  175. // ].join('&');
  176. // }
  177. // }
  178. // let finalResults = [];
  179. request(`https://www.googleapis.com/youtube/v3/search?${params}`, (err, res, body) => {
  180. cb(body);
  181. // for (let i = 0; i < results.items.length; i++) {
  182. // request(`https://www.googleapis.com/youtube/v3/videos?${
  183. // params("video", results.items[i].id.videoId)
  184. // }`, (err, res, body) => {
  185. // finalResults.push(JSON.parse(body));
  186. // });
  187. // }
  188. // setTimeout(() => {
  189. // return cb(finalResults);
  190. // }, 500);
  191. });
  192. },
  193. '/songs/queue/add/:song': (song, user, cb) => {
  194. if (user.logged_in) {
  195. // if (songs.length > 0) {
  196. // let failed = 0;
  197. // let success = 0;
  198. // songs.forEach(function (song) {
  199. // if (typeof song === "object" && song !== null) {
  200. // let obj = {};
  201. // obj.title = song.title;
  202. // obj._id = song.id;
  203. // obj.artists = [];
  204. // obj.image = "test";
  205. // obj.duration = 0;
  206. // obj.genres = ["edm"];
  207. // //TODO Get data from Wikipedia and Spotify
  208. // obj.requestedBy = user._id;
  209. // console.log(user._id);
  210. // console.log(user);
  211. // obj.requestedAt = Date.now();
  212. // let queueSong = new global.db.queueSong(obj);
  213. // queueSong.save(function(err) {
  214. // console.log(err);
  215. // if (err) failed++;
  216. // else success++;
  217. // });
  218. // } else {
  219. // failed++;
  220. // }
  221. // });
  222. // cb({success, failed});
  223. // } else {
  224. // cb({err: "No songs supplied."});
  225. // }
  226. console.log(song);
  227. } else {
  228. cb({err: "Not logged in."});
  229. }
  230. },
  231. '/songs/queue/getSongs': (user, cb) => {
  232. if (user !== null && user !== undefined && user.logged_in) {
  233. global.db.queueSong.find({}, function(err, songs) {
  234. if (err) throw err;
  235. else cb({songs: songs});
  236. });
  237. } else {
  238. cb({err: "Not logged in."});
  239. }
  240. },
  241. '/songs/queue/updateSong/:id': (user, id, object, cb) => {
  242. if (user !== null && user !== undefined && user.logged_in) {
  243. global.db.queueSong.findOne({_id: id}, function(err, song) {
  244. if (err) throw err;
  245. else {
  246. if (song !== undefined && song !== null) {
  247. if (typeof object === "object" && object !== null) {
  248. delete object.requestedBy;
  249. delete object.requestedAt;
  250. global.db.queueSong.update({_id: id}, {$set: object}, function(err, song) {
  251. if (err) throw err;
  252. cb({success: true});
  253. });
  254. } else {
  255. cb({err: "Invalid data."});
  256. }
  257. } else {
  258. cb({err: "Song not found."});
  259. }
  260. }
  261. });
  262. } else {
  263. cb({err: "Not logged in."});
  264. }
  265. },
  266. '/stations/search/:query': (query, cb) => {
  267. const params = [
  268. 'part=snippet',
  269. `q=${encodeURIComponent(query)}`,
  270. `key=${config.get('apis.youtube.key')}`,
  271. 'type=video',
  272. 'maxResults=25'
  273. ].join('&');
  274. request(`https://www.googleapis.com/youtube/v3/search?${params}`, (err, res, body) => {
  275. if (err) {
  276. return cb({ status: 'error', message: 'Failed to make request' });
  277. } else {
  278. try {
  279. return cb({ status: 'success', body: JSON.parse(body) });
  280. }
  281. catch (e) {
  282. return cb({ status: 'error', message: 'Non JSON response' });
  283. }
  284. }
  285. });
  286. },
  287. '/song/:id/toggleLike': (songId, userId, cb) => {
  288. var user = global.db.user.findOne(userId);
  289. var song = global.db.song.findOne(songId);
  290. if (user !== undefined) {
  291. if (song !== undefined) {
  292. var liked = false;
  293. if (song.likes.indexOf(userId) === -1) {
  294. liked = true;
  295. // Add like
  296. } else {
  297. // Remove like
  298. }
  299. if (song.dislikes.indexOf(userId) !== -1) {
  300. // Remove dislike
  301. }
  302. // Emit to all sockets with this user that their likes/dislikes updated.
  303. // Emit to all sockets in the room that the likes/dislikes has updated
  304. cb({liked: liked, disliked: false});
  305. } else {
  306. cb({err: "Song not found."});
  307. }
  308. } else {
  309. cb({err: "User not found."});
  310. }
  311. },
  312. '/user/:id/ratings': (userId, cb) => {
  313. var user = global.db.user.findOne(userId);
  314. if (user !== undefined) {
  315. cb({likes: user.likes, dislikes: user.dislikes});
  316. } else {
  317. cb({err: "User not found."});
  318. }
  319. }
  320. };