server.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. Meteor.startup(function() {
  2. reCAPTCHA.config({
  3. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  4. });
  5. var stations = [{tag: "edm", display: "EDM"}, {tag: "pop", display: "Pop"}]; //Rooms to be set on server startup
  6. for(var i in stations){
  7. if(Rooms.find({type: stations[i]}).count() === 0){
  8. createRoom(stations[i].display, stations[i].tag);
  9. }
  10. }
  11. });
  12. var stations = [];
  13. var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
  14. function createUniqueSongId() {
  15. var code = "";
  16. for (var i = 0; i < 6; i++) {
  17. code += chars[Math.floor(Math.random() * chars.length)];
  18. }
  19. if (Playlists.find({"songs.mid": code}).count() > 0) {
  20. return createUniqueSongId();
  21. } else {
  22. return code;
  23. }
  24. }
  25. function getStation(type, cb) {
  26. stations.forEach(function(station) {
  27. if (station.type === type) {
  28. cb(station);
  29. return;
  30. }
  31. });
  32. }
  33. function createRoom(display, tag) {
  34. var type = tag;
  35. if (Rooms.find({type: type}).count() === 0) {
  36. Rooms.insert({display: display, type: type}, function(err) {
  37. if (err) {
  38. throw err;
  39. } else {
  40. if (Playlists.find({type: type}).count() === 1) {
  41. stations.push(new Station(type));
  42. } else {
  43. Playlists.insert({type: type, songs: getSongsByType(type)}, function (err2) {
  44. if (err2) {
  45. throw err2;
  46. } else {
  47. stations.push(new Station(type));
  48. }
  49. });
  50. }
  51. }
  52. });
  53. } else {
  54. return "Room already exists";
  55. }
  56. }
  57. function Station(type) {
  58. var _this = this;
  59. var startedAt = Date.now();
  60. var playlist = Playlists.findOne({type: type});
  61. var songs = playlist.songs;
  62. if (playlist.lastSong === undefined) {
  63. Playlists.update({type: type}, {$set: {lastSong: 0}});
  64. playlist = Playlists.findOne({type: type});
  65. songs = playlist.songs;
  66. }
  67. var currentSong = playlist.lastSong;
  68. var currentTitle = songs[currentSong].title;
  69. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  70. this.skipSong = function() {
  71. songs = Playlists.findOne({type: type}).songs;
  72. songs.forEach(function(song, index) {
  73. if (song.title === currentTitle) {
  74. currentSong = index;
  75. }
  76. });
  77. if (currentSong < (songs.length - 1)) {
  78. currentSong++;
  79. } else currentSong = 0;
  80. if (songs);
  81. if (currentSong === 0) {
  82. this.shufflePlaylist();
  83. } else {
  84. if (songs[currentSong].mid === undefined) {
  85. var newSong = songs[currentSong];
  86. newSong.mid = createUniqueSongId();
  87. songs[currentSong].mid = newSong.mid;
  88. Playlists.update({type: type, "songs": songs[currentSong]}, {$set: {"songs.$": newSong}});
  89. }
  90. if (songs[currentSong].likes === undefined) {
  91. var newSong = songs[currentSong];
  92. newSong.likes = 0;
  93. Playlists.update({type: type, "songs": newSong}, {$set: {"songs.$": newSong}});
  94. }
  95. if (songs[currentSong].dislikes === undefined) {
  96. var newSong = songs[currentSong];
  97. newSong.dislikes = 0;
  98. Playlists.update({type: type, "songs": newSong}, {$set: {"songs.$": newSong}});
  99. }
  100. currentTitle = songs[currentSong].title;
  101. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  102. Rooms.update({type: type}, {$set: {timePaused: 0}});
  103. this.songTimer();
  104. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  105. }
  106. };
  107. this.shufflePlaylist = function() {
  108. songs = Playlists.findOne({type: type}).songs;
  109. currentSong = 0;
  110. Playlists.update({type: type}, {$set: {"songs": []}});
  111. songs = shuffle(songs);
  112. songs.forEach(function(song) {
  113. if (song.mid === undefined) {
  114. song.mid = createUniqueSongId();
  115. }
  116. if (song.likes === undefined) {
  117. song.likes = 0;
  118. }
  119. if (song.dislikes === undefined) {
  120. song.dislikes = 0;
  121. }
  122. Playlists.update({type: type}, {$push: {"songs": song}});
  123. });
  124. currentTitle = songs[currentSong].title;
  125. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  126. Rooms.update({type: type}, {$set: {timePaused: 0}});
  127. this.songTimer();
  128. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  129. };
  130. Rooms.update({type: type}, {$set: {timePaused: 0}});
  131. var timer;
  132. this.songTimer = function() {
  133. startedAt = Date.now();
  134. if (timer !== undefined) {
  135. timer.pause();
  136. }
  137. timer = new Timer(function() {
  138. _this.skipSong();
  139. }, songs[currentSong].duration * 1000);
  140. };
  141. var state = Rooms.findOne({type: type}).state;
  142. this.pauseRoom = function() {
  143. if (state !== "paused") {
  144. timer.pause();
  145. Rooms.update({type: type}, {$set: {state: "paused"}});
  146. state = "paused";
  147. }
  148. };
  149. this.resumeRoom = function() {
  150. if (state !== "playing") {
  151. timer.resume();
  152. Rooms.update({type: type}, {$set: {state: "playing", timePaused: timer.timeWhenPaused()}});
  153. state = "playing";
  154. }
  155. };
  156. this.cancelTimer = function() {
  157. timer.pause();
  158. };
  159. this.getState = function() {
  160. return state;
  161. };
  162. this.type = type;
  163. this.songTimer();
  164. }
  165. function shuffle(array) {
  166. var currentIndex = array.length, temporaryValue, randomIndex ;
  167. // While there remain elements to shuffle...
  168. while (0 !== currentIndex) {
  169. // Pick a remaining element...
  170. randomIndex = Math.floor(Math.random() * currentIndex);
  171. currentIndex -= 1;
  172. // And swap it with the current element.
  173. temporaryValue = array[currentIndex];
  174. array[currentIndex] = array[randomIndex];
  175. array[randomIndex] = temporaryValue;
  176. }
  177. return array;
  178. }
  179. function Timer(callback, delay) {
  180. var timerId, start, remaining = delay;
  181. var timeWhenPaused = 0;
  182. var timePaused = new Date();
  183. this.pause = function() {
  184. Meteor.clearTimeout(timerId);
  185. remaining -= new Date() - start;
  186. timePaused = new Date();
  187. };
  188. this.resume = function() {
  189. start = new Date();
  190. Meteor.clearTimeout(timerId);
  191. timerId = Meteor.setTimeout(callback, remaining);
  192. timeWhenPaused += new Date() - timePaused;
  193. };
  194. this.timeWhenPaused = function() {
  195. return timeWhenPaused;
  196. };
  197. this.resume();
  198. }
  199. Meteor.users.deny({update: function () { return true; }});
  200. Meteor.users.deny({insert: function () { return true; }});
  201. Meteor.users.deny({remove: function () { return true; }});
  202. function getSongDuration(query, artistName){
  203. var duration;
  204. var search = query;
  205. query = query.toLowerCase().split(" ").join("%20");
  206. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  207. for(var i in res.data){
  208. for(var j in res.data[i].items){
  209. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  210. duration = res.data[i].items[j].duration_ms / 1000;
  211. return duration;
  212. }
  213. }
  214. }
  215. }
  216. function getSongAlbumArt(query, artistName){
  217. var albumart;
  218. var search = query;
  219. query = query.toLowerCase().split(" ").join("%20");
  220. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  221. for(var i in res.data){
  222. for(var j in res.data[i].items){
  223. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  224. albumart = res.data[i].items[j].album.images[1].url
  225. return albumart;
  226. }
  227. }
  228. }
  229. }
  230. //var room_types = ["edm", "nightcore"];
  231. var songsArr = [];
  232. function getSongsByType(type) {
  233. if (type === "edm") {
  234. return [
  235. {id: "aE2GCa-_nyU", mid: "fh6_Gf", title: "Radioactive", duration: getSongDuration("Radioactive - Lindsey Stirling and Pentatonix", "Lindsey Stirling, Pentatonix"), artist: "Lindsey Stirling, Pentatonix", type: "YouTube", img: "https://i.scdn.co/image/62167a9007cef2e8ef13ab1d93019312b9b03655"},
  236. {id: "aHjpOzsQ9YI", mid: "goG88g", title: "Crystallize", artist: "Lindsey Stirling", duration: getSongDuration("Crystallize", "Lindsey Stirling"), type: "YouTube", img: "https://i.scdn.co/image/b0c1ccdd0cd7bcda741ccc1c3e036f4ed2e52312"}
  237. ];
  238. } else if (type === "nightcore") {
  239. return [{id: "f7RKOP87tt4", mid: "5pGGog", title: "Monster (DotEXE Remix)", duration: getSongDuration("Monster (DotEXE Remix)", "Meg & Dia"), artist: "Meg & Dia", type: "YouTube", img: "https://i.scdn.co/image/35ecdfba9c31a6c54ee4c73dcf1ad474c560cd00"}];
  240. } else {
  241. return [{id: "dQw4w9WgXcQ", mid: "6_fdr4", title: "Never Gonna Give You Up", duration: getSongDuration("Never Gonna Give You Up", "Rick Astley"), artist: "Rick Astley", type: "YouTube", img: "https://i.scdn.co/image/5246898e19195715e65e261899baba890a2c1ded"}];
  242. }
  243. }
  244. Rooms.find({}).fetch().forEach(function(room) {
  245. var type = room.type;
  246. if (Playlists.find({type: type}).count() === 0) {
  247. if (type === "edm") {
  248. Playlists.insert({type: type, songs: getSongsByType(type)});
  249. } else if (type === "nightcore") {
  250. Playlists.insert({type: type, songs: getSongsByType(type)});
  251. } else {
  252. Playlists.insert({type: type, songs: getSongsByType(type)});
  253. }
  254. }
  255. if (Playlists.findOne({type: type}).songs.length === 0) {
  256. // Add a global video to Playlist so it can proceed
  257. } else {
  258. stations.push(new Station(type));
  259. }
  260. });
  261. Accounts.validateNewUser(function(user) {
  262. var username;
  263. if (user.services) {
  264. if (user.services.github) {
  265. username = user.services.github.username;
  266. } else if (user.services.facebook) {
  267. username = user.services.facebook.first_name;
  268. } else if (user.services.password) {
  269. username = user.username;
  270. }
  271. }
  272. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() !== 0) {
  273. throw new Meteor.Error(403, "An account with that username already exists.");
  274. } else {
  275. return true;
  276. }
  277. });
  278. Accounts.onCreateUser(function(options, user) {
  279. var username;
  280. if (user.services) {
  281. if (user.services.github) {
  282. username = user.services.github.username;
  283. } else if (user.services.facebook) {
  284. username = user.services.facebook.first_name;
  285. } else if (user.services.password) {
  286. username = user.username;
  287. }
  288. }
  289. user.profile = {username: username, usernameL: username.toLowerCase(), rank: "default", liked: [], disliked: []};
  290. return user;
  291. });
  292. ServiceConfiguration.configurations.remove({
  293. service: "facebook"
  294. });
  295. ServiceConfiguration.configurations.insert({
  296. service: "facebook",
  297. appId: "1496014310695890",
  298. secret: "9a039f254a08a1488c08bb0737dbd2a6"
  299. });
  300. ServiceConfiguration.configurations.remove({
  301. service: "github"
  302. });
  303. ServiceConfiguration.configurations.insert({
  304. service: "github",
  305. clientId: "dcecd720f47c0e4001f7",
  306. secret: "375939d001ef1a0ca67c11dbf8fb9aeaa551e01b"
  307. });
  308. Meteor.publish("playlists", function() {
  309. return Playlists.find({})
  310. });
  311. Meteor.publish("rooms", function() {
  312. return Rooms.find({});
  313. });
  314. Meteor.publish("queues", function() {
  315. return Queues.find({});
  316. });
  317. Meteor.publish("chat", function() {
  318. return Chat.find({});
  319. });
  320. Meteor.publish("userProfiles", function() {
  321. return Meteor.users.find({}, {fields: {profile: 1, createdAt: 1}});
  322. });
  323. Meteor.publish("isAdmin", function() {
  324. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  325. });
  326. function isAdmin() {
  327. var userData = Meteor.users.find(Meteor.userId());
  328. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  329. return true;
  330. } else {
  331. return false;
  332. }
  333. }
  334. Meteor.methods({
  335. likeSong: function(mid) {
  336. if (Meteor.userId()) {
  337. var user = Meteor.user();
  338. if (user.profile.liked.indexOf(mid) === -1) {
  339. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  340. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": 1}})
  341. } else {
  342. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  343. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}})
  344. }
  345. if (user.profile.disliked.indexOf(mid) !== -1) {
  346. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  347. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}})
  348. }
  349. return true;
  350. } else {
  351. throw new Meteor.Error(403, "Invalid permissions.");
  352. }
  353. },
  354. dislikeSong: function(mid) {
  355. if (Meteor.userId()) {
  356. var user = Meteor.user();
  357. if (user.profile.disliked.indexOf(mid) === -1) {
  358. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  359. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": 1}});
  360. } else {
  361. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  362. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}});
  363. }
  364. if (user.profile.liked.indexOf(mid) !== -1) {
  365. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  366. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}});
  367. }
  368. return true;
  369. } else {
  370. throw new Meteor.Error(403, "Invalid permissions.");
  371. }
  372. },
  373. submitReport: function(report, id) {
  374. var obj = report;
  375. obj.id = id;
  376. Reports.insert(obj);
  377. },
  378. shufflePlaylist: function(type) {
  379. if (isAdmin()) {
  380. getStation(type, function(station) {
  381. if (station === undefined) {
  382. throw new Meteor.Error(404, "Station not found.");
  383. } else {
  384. station.cancelTimer();
  385. station.shufflePlaylist();
  386. }
  387. });
  388. }
  389. },
  390. skipSong: function(type) {
  391. if (isAdmin()) {
  392. getStation(type, function(station) {
  393. if (station === undefined) {
  394. throw new Meteor.Error(404, "Station not found.");
  395. } else {
  396. station.skipSong();
  397. }
  398. });
  399. }
  400. },
  401. pauseRoom: function(type) {
  402. if (isAdmin()) {
  403. getStation(type, function(station) {
  404. if (station === undefined) {
  405. throw new Meteor.Error(403, "Room doesn't exist.");
  406. } else {
  407. station.pauseRoom();
  408. }
  409. });
  410. } else {
  411. throw new Meteor.Error(403, "Invalid permissions.");
  412. }
  413. },
  414. resumeRoom: function(type) {
  415. if (isAdmin()) {
  416. getStation(type, function(station) {
  417. if (station === undefined) {
  418. throw new Meteor.Error(403, "Room doesn't exist.");
  419. } else {
  420. station.resumeRoom();
  421. }
  422. });
  423. } else {
  424. throw new Meteor.Error(403, "Invalid permissions.");
  425. }
  426. },
  427. createUserMethod: function(formData, captchaData) {
  428. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  429. if (!verifyCaptchaResponse.success) {
  430. console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
  431. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  432. } else {
  433. console.log('reCAPTCHA verification passed!');
  434. Accounts.createUser({
  435. username: formData.username,
  436. email: formData.email,
  437. password: formData.password
  438. });
  439. }
  440. return true;
  441. },
  442. addSongToQueue: function(type, songData) {
  443. if (Meteor.userId()) {
  444. type = type.toLowerCase();
  445. if (Rooms.find({type: type}).count() === 1) {
  446. if (Queues.find({type: type}).count() === 0) {
  447. Queues.insert({type: type, songs: []});
  448. }
  449. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  450. songData.duration = getSongDuration(songData.title, songData.artist);
  451. songData.img = getSongAlbumArt(songData.title, songData.artist);
  452. var mid = createUniqueSongId();
  453. if (mid !== undefined) {
  454. songData.mid = mid;
  455. Queues.update({type: type}, {
  456. $push: {
  457. songs: {
  458. id: songData.id,
  459. mid: songData.mid,
  460. title: songData.title,
  461. artist: songData.artist,
  462. duration: songData.duration,
  463. img: songData.img,
  464. type: songData.type
  465. }
  466. }
  467. });
  468. return true;
  469. } else {
  470. throw new Meteor.Error(500, "Am error occured.");
  471. }
  472. } else {
  473. throw new Meteor.Error(403, "Invalid data.");
  474. }
  475. } else {
  476. throw new Meteor.Error(403, "Invalid genre.");
  477. }
  478. } else {
  479. throw new Meteor.Error(403, "Invalid permissions.");
  480. }
  481. },
  482. updateQueueSong: function(genre, oldSong, newSong) {
  483. if (isAdmin()) {
  484. newSong.mid = oldSong.mid;
  485. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  486. return true;
  487. } else {
  488. throw new Meteor.Error(403, "Invalid permissions.");
  489. }
  490. },
  491. updatePlaylistSong: function(genre, oldSong, newSong) {
  492. if (isAdmin()) {
  493. newSong.mid = oldSong.mid;
  494. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  495. return true;
  496. } else {
  497. throw new Meteor.Error(403, "Invalid permissions.");
  498. }
  499. },
  500. removeSongFromQueue: function(type, mid) {
  501. if (isAdmin()) {
  502. type = type.toLowerCase();
  503. Queues.update({type: type}, {$pull: {songs: {mid: mid}}});
  504. } else {
  505. throw new Meteor.Error(403, "Invalid permissions.");
  506. }
  507. },
  508. removeSongFromPlaylist: function(type, mid) {
  509. if (isAdmin()) {
  510. type = type.toLowerCase();
  511. Playlists.update({type: type}, {$pull: {songs: {mid: mid}}});
  512. } else {
  513. throw new Meteor.Error(403, "Invalid permissions.");
  514. }
  515. },
  516. addSongToPlaylist: function(type, songData) {
  517. if (isAdmin()) {
  518. type = type.toLowerCase();
  519. if (Rooms.find({type: type}).count() === 1) {
  520. if (Playlists.find({type: type}).count() === 0) {
  521. Playlists.insert({type: type, songs: []});
  522. }
  523. if (songData !== undefined && Object.keys(songData).length === 7 && songData.type !== undefined && songData.mid !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.duration !== undefined && songData.img !== undefined) {
  524. songData.likes = 0;
  525. songData.dislikes = 0
  526. Playlists.update({type: type}, {
  527. $push: {
  528. songs: {
  529. id: songData.id,
  530. mid: songData.mid,
  531. title: songData.title,
  532. artist: songData.artist,
  533. duration: songData.duration,
  534. img: songData.img,
  535. type: songData.type,
  536. likes: songData.likes,
  537. dislikes: songData.dislikes
  538. }
  539. }
  540. });
  541. Queues.update({type: type}, {$pull: {songs: {mid: songData.mid}}});
  542. return true;
  543. } else {
  544. throw new Meteor.Error(403, "Invalid data.");
  545. }
  546. } else {
  547. throw new Meteor.Error(403, "Invalid genre.");
  548. }
  549. } else {
  550. throw new Meteor.Error(403, "Invalid permissions.");
  551. }
  552. },
  553. createRoom: function(display, tag) {
  554. if (isAdmin()) {
  555. createRoom(display, tag);
  556. } else {
  557. throw new Meteor.Error(403, "Invalid permissions.");
  558. }
  559. },
  560. deleteRoom: function(type){
  561. if (isAdmin()) {
  562. Rooms.remove({type: type});
  563. Playlists.remove({type: type});
  564. Queues.remove({type: type});
  565. return true;
  566. } else {
  567. throw new Meteor.Error(403, "Invalid permissions.");
  568. }
  569. },
  570. getUserNum: function(){
  571. return Object.keys(Meteor.default_server.sessions).length;
  572. }
  573. });