server.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. Meteor.startup(function() {
  2. reCAPTCHA.config({
  3. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  4. });
  5. Avatar.setOptions({
  6. fallbackType: "initials",
  7. defaultImageUrl: "http://static.boredpanda.com/blog/wp-content/uploads/2014/04/amazing-fox-photos-182.jpg",
  8. generateCSS: true,
  9. imageSizes: {
  10. 'header': 40
  11. }
  12. });
  13. var stations = [{tag: "edm", display: "EDM"}, {tag: "pop", display: "Pop"}]; //Rooms to be set on server startup
  14. for(var i in stations){
  15. if(Rooms.find({type: stations[i]}).count() === 0){
  16. createRoom(stations[i].display, stations[i].tag);
  17. }
  18. }
  19. emojione.ascii = true;
  20. });
  21. Alerts.update({active: true}, {$set: {active: false}}, { multi: true });
  22. var stations = [];
  23. var voteNum = 0;
  24. var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
  25. function createUniqueSongId() {
  26. var code = "";
  27. for (var i = 0; i < 6; i++) {
  28. code += chars[Math.floor(Math.random() * chars.length)];
  29. }
  30. if (Playlists.find({"songs.mid": code}).count() > 0) {
  31. return createUniqueSongId();
  32. } else {
  33. return code;
  34. }
  35. }
  36. function checkUsersPR() {
  37. var output = {};
  38. var connections = Meteor.server.stream_server.open_sockets;
  39. _.each(connections,function(connection){
  40. // named subscriptions
  41. if (connection._meteorSession !== undefined) {
  42. var subs = connection._meteorSession._namedSubs;
  43. //var ip = connection.remoteAddress;
  44. var used_subs = [];
  45. for (var sub in subs) {
  46. var mySubName = subs[sub]._name;
  47. if (subs[sub]._params.length > 0) {
  48. mySubName += subs[sub]._params[0]; // assume one id parameter for now
  49. }
  50. if (used_subs.indexOf(mySubName) === -1) {
  51. used_subs.push(mySubName);
  52. if (!output[mySubName]) {
  53. output[mySubName] = 1;
  54. } else {
  55. output[mySubName] += 1;
  56. }
  57. }
  58. }
  59. }
  60. // there are also these 'universal subscriptions'
  61. //not sure what these are, i count none in my tests
  62. //var usubs = connection._meteorSession._universalSubs;
  63. });
  64. for (var key in output) {
  65. getStation(key, function() {
  66. Rooms.update({type: key}, {$set: {users: output[key]}});
  67. });
  68. }
  69. return output;
  70. }
  71. function getStation(type, cb) {
  72. stations.forEach(function(station) {
  73. if (station.type === type) {
  74. cb(station);
  75. return;
  76. }
  77. });
  78. }
  79. function createRoom(display, tag) {
  80. var type = tag;
  81. if (Rooms.find({type: type}).count() === 0) {
  82. Rooms.insert({display: display, type: type, users: 0}, function(err) {
  83. if (err) {
  84. throw err;
  85. } else {
  86. if (Playlists.find({type: type}).count() === 1) {
  87. stations.push(new Station(type));
  88. } else {
  89. Playlists.insert({type: type, songs: getSongsByType(type)}, function (err2) {
  90. if (err2) {
  91. throw err2;
  92. } else {
  93. stations.push(new Station(type));
  94. }
  95. });
  96. }
  97. }
  98. });
  99. } else {
  100. return "Room already exists";
  101. }
  102. }
  103. function Station(type) {
  104. Meteor.publish(type, function() {
  105. return undefined;
  106. });
  107. var self = this;
  108. var startedAt = Date.now();
  109. var playlist = Playlists.findOne({type: type});
  110. var songs = playlist.songs;
  111. if (playlist.lastSong === undefined) {
  112. Playlists.update({type: type}, {$set: {lastSong: 0}});
  113. playlist = Playlists.findOne({type: type});
  114. songs = playlist.songs;
  115. }
  116. var currentSong = playlist.lastSong;
  117. if (currentSong < (songs.length - 1)) {
  118. currentSong++;
  119. } else currentSong = 0;
  120. var currentTitle = songs[currentSong].title;
  121. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}, users: 0}});
  122. this.skipSong = function() {
  123. self.voted = [];
  124. voteNum = 0;
  125. Rooms.update({type: type}, {$set: {votes: 0}});
  126. songs = Playlists.findOne({type: type}).songs;
  127. songs.forEach(function(song, index) {
  128. if (song.title === currentTitle) {
  129. currentSong = index;
  130. }
  131. });
  132. if (currentSong < (songs.length - 1)) {
  133. currentSong++;
  134. } else currentSong = 0;
  135. if (songs);
  136. if (currentSong === 0) {
  137. this.shufflePlaylist();
  138. } else {
  139. if (songs[currentSong].mid === undefined) {
  140. var newSong = songs[currentSong];
  141. newSong.mid = createUniqueSongId();
  142. songs[currentSong].mid = newSong.mid;
  143. Playlists.update({type: type, "songs": songs[currentSong]}, {$set: {"songs.$": newSong}});
  144. }
  145. currentTitle = songs[currentSong].title;
  146. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  147. Rooms.update({type: type}, {$set: {timePaused: 0}});
  148. this.songTimer();
  149. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  150. }
  151. };
  152. this.shufflePlaylist = function() {
  153. voteNum = 0;
  154. Rooms.update({type: type}, {$set: {votes: 0}});
  155. self.voted = [];
  156. songs = Playlists.findOne({type: type}).songs;
  157. currentSong = 0;
  158. Playlists.update({type: type}, {$set: {"songs": []}});
  159. songs = shuffle(songs);
  160. songs.forEach(function(song) {
  161. if (song.mid === undefined) {
  162. song.mid = createUniqueSongId();
  163. }
  164. Playlists.update({type: type}, {$push: {"songs": song}});
  165. });
  166. currentTitle = songs[currentSong].title;
  167. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  168. Rooms.update({type: type}, {$set: {timePaused: 0}});
  169. this.songTimer();
  170. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  171. };
  172. Rooms.update({type: type}, {$set: {timePaused: 0}});
  173. var timer;
  174. this.songTimer = function() {
  175. startedAt = Date.now();
  176. if (timer !== undefined) {
  177. timer.pause();
  178. }
  179. timer = new Timer(function() {
  180. self.skipSong();
  181. }, songs[currentSong].duration * 1000);
  182. };
  183. var state = Rooms.findOne({type: type}).state;
  184. this.pauseRoom = function() {
  185. if (state !== "paused") {
  186. timer.pause();
  187. Rooms.update({type: type}, {$set: {state: "paused"}});
  188. state = "paused";
  189. }
  190. };
  191. this.resumeRoom = function() {
  192. if (state !== "playing") {
  193. timer.resume();
  194. Rooms.update({type: type}, {$set: {state: "playing", timePaused: timer.timeWhenPaused()}});
  195. state = "playing";
  196. }
  197. };
  198. this.cancelTimer = function() {
  199. timer.pause();
  200. };
  201. this.getState = function() {
  202. return state;
  203. };
  204. this.type = type;
  205. var private = Rooms.findOne({type: type}).private;
  206. if (typeof private !== "boolean") {
  207. Rooms.update({type: type}, {$set: {"private": false}});
  208. private = false;
  209. }
  210. this.private = private;
  211. this.unlock = function() {
  212. if (self.private) {
  213. self.private = false;
  214. Rooms.update({type: type}, {$set: {"private": false}});
  215. }
  216. };
  217. this.lock = function() {
  218. if (!self.private) {
  219. self.private = true;
  220. Rooms.update({type: type}, {$set: {"private": true}});
  221. }
  222. };
  223. this.songTimer();
  224. this.voted = [];
  225. }
  226. function shuffle(array) {
  227. var currentIndex = array.length, temporaryValue, randomIndex ;
  228. // While there remain elements to shuffle...
  229. while (0 !== currentIndex) {
  230. // Pick a remaining element...
  231. randomIndex = Math.floor(Math.random() * currentIndex);
  232. currentIndex -= 1;
  233. // And swap it with the current element.
  234. temporaryValue = array[currentIndex];
  235. array[currentIndex] = array[randomIndex];
  236. array[randomIndex] = temporaryValue;
  237. }
  238. return array;
  239. }
  240. function Timer(callback, delay) {
  241. var timerId, start, remaining = delay;
  242. var timeWhenPaused = 0;
  243. var timePaused = new Date();
  244. this.pause = function() {
  245. Meteor.clearTimeout(timerId);
  246. remaining -= new Date() - start;
  247. timePaused = new Date();
  248. };
  249. this.resume = function() {
  250. start = new Date();
  251. Meteor.clearTimeout(timerId);
  252. timerId = Meteor.setTimeout(callback, remaining);
  253. timeWhenPaused += new Date() - timePaused;
  254. };
  255. this.timeWhenPaused = function() {
  256. return timeWhenPaused;
  257. };
  258. this.resume();
  259. }
  260. Meteor.users.deny({update: function () { return true; }});
  261. Meteor.users.deny({insert: function () { return true; }});
  262. Meteor.users.deny({remove: function () { return true; }});
  263. function getSongDuration(query, artistName){
  264. var duration;
  265. var search = query;
  266. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  267. for(var i in res.data){
  268. for(var j in res.data[i].items){
  269. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  270. duration = res.data[i].items[j].duration_ms / 1000;
  271. return duration;
  272. }
  273. }
  274. }
  275. }
  276. function getSongAlbumArt(query, artistName){
  277. var albumart;
  278. var search = query;
  279. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  280. for(var i in res.data){
  281. for(var j in res.data[i].items){
  282. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  283. albumart = res.data[i].items[j].album.images[1].url
  284. return albumart;
  285. }
  286. }
  287. }
  288. }
  289. //var room_types = ["edm", "nightcore"];
  290. var songsArr = [];
  291. function getSongsByType(type) {
  292. if (type === "edm") {
  293. return [
  294. {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"},
  295. {id: "aHjpOzsQ9YI", mid: "goG88g", title: "Crystallize", artist: "Lindsey Stirling", duration: getSongDuration("Crystallize", "Lindsey Stirling"), type: "YouTube", img: "https://i.scdn.co/image/b0c1ccdd0cd7bcda741ccc1c3e036f4ed2e52312"}
  296. ];
  297. } else if (type === "nightcore") {
  298. 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"}];
  299. } else {
  300. 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"}];
  301. }
  302. }
  303. Rooms.find({}).fetch().forEach(function(room) {
  304. var type = room.type;
  305. if (Playlists.find({type: type}).count() === 0) {
  306. if (type === "edm") {
  307. Playlists.insert({type: type, songs: getSongsByType(type)});
  308. } else if (type === "nightcore") {
  309. Playlists.insert({type: type, songs: getSongsByType(type)});
  310. } else {
  311. Playlists.insert({type: type, songs: getSongsByType(type)});
  312. }
  313. }
  314. if (Playlists.findOne({type: type}).songs.length === 0) {
  315. // Add a global video to Playlist so it can proceed
  316. } else {
  317. stations.push(new Station(type));
  318. }
  319. });
  320. Accounts.validateNewUser(function(user) {
  321. var username;
  322. if (user.services) {
  323. if (user.services.github) {
  324. username = user.services.github.username;
  325. } else if (user.services.facebook) {
  326. username = user.services.facebook.first_name;
  327. } else if (user.services.password) {
  328. username = user.username;
  329. }
  330. }
  331. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() !== 0) {
  332. throw new Meteor.Error(403, "An account with that username already exists.");
  333. } else {
  334. return true;
  335. }
  336. });
  337. Accounts.onCreateUser(function(options, user) {
  338. var username;
  339. if (user.services) {
  340. if (user.services.github) {
  341. username = user.services.github.username;
  342. } else if (user.services.facebook) {
  343. username = user.services.facebook.first_name;
  344. } else if (user.services.password) {
  345. username = user.username;
  346. }
  347. }
  348. user.profile = {username: username, usernameL: username.toLowerCase(), rank: "default", liked: [], disliked: [], settings: {showRating: false}};
  349. return user;
  350. });
  351. Meteor.publish("alerts", function() {
  352. return Alerts.find({active: true})
  353. });
  354. Meteor.publish("userData", function(userId) {
  355. if (userId !== undefined) {
  356. return Meteor.users.find(userId, {fields: {"services.github.username": 1, "punishments": 1}})
  357. } else {
  358. return undefined;
  359. }
  360. });
  361. Meteor.publish("allAlerts", function() {
  362. return Alerts.find({active: false})
  363. });
  364. Meteor.publish("playlists", function() {
  365. return Playlists.find({})
  366. });
  367. Meteor.publish("rooms", function() {
  368. return Rooms.find({});
  369. });
  370. Meteor.publish("queues", function() {
  371. return Queues.find({});
  372. });
  373. Meteor.publish("reports", function() {
  374. return Reports.find({});
  375. });
  376. Meteor.publish("chat", function() {
  377. return Chat.find({});
  378. });
  379. Meteor.publish("userProfiles", function(username) {
  380. var settings = Meteor.users.findOne({"profile.usernameL": username}, {fields: {"profile.settings": 1}});
  381. if (settings !== undefined && settings.profile.settings) {
  382. settings = settings.profile.settings;
  383. if (settings.showRating === true) {
  384. return Meteor.users.find({"profile.usernameL": username}, {fields: {"profile.username": 1, "profile.usernameL": 1, "profile.rank": 1, createdAt: 1, "profile.liked": 1, "profile.disliked": 1, "profile.settings": 1}});
  385. }
  386. }
  387. return Meteor.users.find({"profile.usernameL": username}, {fields: {"profile.username": 1, "profile.usernameL": 1, "profile.rank": 1, createdAt: 1, "profile.settings": 1}});
  388. });
  389. Meteor.publish("isAdmin", function() {
  390. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  391. });
  392. Meteor.publish("isModerator", function() {
  393. return Meteor.users.find({_id: this.userId, "profile.rank": "moderator"});
  394. });
  395. function isAdmin() {
  396. var userData = Meteor.users.find(Meteor.userId());
  397. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  398. return true;
  399. } else {
  400. return false;
  401. }
  402. }
  403. function isModerator() {
  404. var userData = Meteor.users.find(Meteor.userId());
  405. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  406. return true;
  407. } else {
  408. return isAdmin();
  409. }
  410. }
  411. function isBanned() {
  412. var userData = Meteor.users.findOne(Meteor.userId());
  413. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  414. var ban = userData.punishments.ban;
  415. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  416. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  417. return false;
  418. } else {
  419. return true;
  420. }
  421. } else {
  422. return false;
  423. }
  424. }
  425. Meteor.methods({
  426. lockRoom: function(type) {
  427. if (isAdmin() && !isBanned()) {
  428. getStation(type, function(station){
  429. station.lock();
  430. });
  431. } else {
  432. throw new Meteor.Error(403, "Invalid permissions.");
  433. }
  434. },
  435. unlockRoom: function(type) {
  436. if (isAdmin() && !isBanned()) {
  437. getStation(type, function(station){
  438. station.unlock();
  439. });
  440. } else {
  441. throw new Meteor.Error(403, "Invalid permissions.");
  442. }
  443. },
  444. banUser: function(username, period, reason) {
  445. if (isAdmin() && !isBanned()) {
  446. var user = Meteor.user();
  447. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  448. var bannedUntil = (new Date).getTime() + (period * 1000);
  449. if (bannedUntil > 8640000000000000) {
  450. bannedUntil = 8640000000000000;
  451. }
  452. bannedUntil = new Date(bannedUntil);
  453. var banObject = {bannedBy: user.profile.usernameL, bannedAt: new Date(Date.now()), bannedReason: reason, bannedUntil: bannedUntil};
  454. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  455. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  456. } else {
  457. throw new Meteor.Error(403, "Invalid permissions.");
  458. }
  459. },
  460. isBanned: function() {
  461. return isBanned();
  462. },
  463. updateSettings: function(showRating) {
  464. if (Meteor.userId() && !isBanned()) {
  465. var user = Meteor.user();
  466. if (showRating !== true && showRating !== false) {
  467. showRating = false;
  468. }
  469. if (user.profile.settings) {
  470. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  471. } else {
  472. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  473. }
  474. } else {
  475. throw new Meteor.Error(403, "Invalid permissions.");
  476. }
  477. },
  478. resetRating: function() {
  479. if (isAdmin() && !isBanned()) {
  480. stations.forEach(function (station) {
  481. var type = station.type;
  482. var temp_songs = Playlists.findOne({type: type}).songs;
  483. Playlists.update({type: type}, {$set: {"songs": []}});
  484. temp_songs.forEach(function (song) {
  485. song.likes = 0;
  486. song.dislikes = 0;
  487. Playlists.update({type: type}, {$push: {"songs": song}});
  488. });
  489. });
  490. Meteor.users.update({}, {$set: {"profile.liked": [], "profile.disliked": []}}, {multi: true});
  491. } else {
  492. throw Meteor.Error(403, "Invalid permissions.");
  493. }
  494. },
  495. removeAlerts: function() {
  496. if (isAdmin() && !isBanned()) {
  497. Alerts.update({active: true}, {$set: {active: false}}, { multi: true });
  498. } else {
  499. throw Meteor.Error(403, "Invalid permissions.");
  500. }
  501. },
  502. addAlert: function(description, priority) {
  503. if (isAdmin()) {
  504. if (description.length > 0 && description.length < 400) {
  505. var username = Meteor.user().profile.username;
  506. if (["danger", "warning", "success", "primary"].indexOf(priority) === -1) {
  507. priority = "warning";
  508. }
  509. Alerts.insert({description: description, priority: priority, active: true, createdBy: username});
  510. return true;
  511. } else {
  512. throw Meteor.Error(403, "Invalid description length.");
  513. }
  514. } else {
  515. throw Meteor.Error(403, "Invalid permissions.");
  516. }
  517. },
  518. sendMessage: function(type, message) {
  519. if (Meteor.userId() && !isBanned()) {
  520. var user = Meteor.user();
  521. var time = new Date();
  522. var rawrank = user.profile.rank;
  523. var username = user.profile.username;
  524. if (!message.replace(/\s/g, "").length > 0) {
  525. throw new Meteor.Error(406, "Message length cannot be 0.");
  526. }
  527. if (message.length > 300) {
  528. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  529. }
  530. else if (user.profile.rank === "admin") {
  531. Chat.insert({type: type, rawrank: rawrank, rank: "[A]", message: message, time: time, username: username});
  532. return true;
  533. }
  534. else if (user.profile.rank === "moderator") {
  535. Chat.insert({type: type, rawrank: rawrank, rank: "[M]", message: message, time: time, username: username});
  536. return true;
  537. }
  538. else {
  539. Chat.insert({type: type, rawrank: rawrank, message: message, time: time, username: username});
  540. return true;
  541. }
  542. } else {
  543. throw new Meteor.Error(403, "Invalid permissions.");
  544. }
  545. },
  546. likeSong: function(mid) {
  547. if (Meteor.userId() && !isBanned()) {
  548. var user = Meteor.user();
  549. if (user.profile.liked.indexOf(mid) === -1) {
  550. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  551. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": 1}})
  552. } else {
  553. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  554. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}})
  555. }
  556. if (user.profile.disliked.indexOf(mid) !== -1) {
  557. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  558. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}})
  559. }
  560. return true;
  561. } else {
  562. throw new Meteor.Error(403, "Invalid permissions.");
  563. }
  564. },
  565. dislikeSong: function(mid) {
  566. if (Meteor.userId() && !isBanned()) {
  567. var user = Meteor.user();
  568. if (user.profile.disliked.indexOf(mid) === -1) {
  569. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  570. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": 1}});
  571. } else {
  572. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  573. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}});
  574. }
  575. if (user.profile.liked.indexOf(mid) !== -1) {
  576. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  577. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}});
  578. }
  579. return true;
  580. } else {
  581. throw new Meteor.Error(403, "Invalid permissions.");
  582. }
  583. },
  584. voteSkip: function(type){
  585. if(Meteor.userId() && !isBanned()){
  586. var user = Meteor.user();
  587. getStation(type, function(station){
  588. if(station.voted.indexOf(user.profile.username) === -1){
  589. station.voted.push(user.profile.username);
  590. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  591. if(station.voted.length === 3){
  592. station.skipSong();
  593. }
  594. } else{
  595. throw new Meteor.Error(401, "Already voted.");
  596. }
  597. })
  598. }
  599. },
  600. submitReport: function(report, id) {
  601. if (!isBanned()) {
  602. var obj = report;
  603. obj.id = id;
  604. Reports.insert(obj);
  605. }
  606. },
  607. shufflePlaylist: function(type) {
  608. if (isAdmin() && !isBanned()) {
  609. getStation(type, function(station) {
  610. if (station === undefined) {
  611. throw new Meteor.Error(404, "Station not found.");
  612. } else {
  613. station.cancelTimer();
  614. station.shufflePlaylist();
  615. }
  616. });
  617. }
  618. },
  619. skipSong: function(type) {
  620. if (isAdmin() && !isBanned()) {
  621. getStation(type, function(station) {
  622. if (station === undefined) {
  623. throw new Meteor.Error(404, "Station not found.");
  624. } else {
  625. station.skipSong();
  626. }
  627. });
  628. }
  629. },
  630. pauseRoom: function(type) {
  631. if (isAdmin() && !isBanned()) {
  632. getStation(type, function(station) {
  633. if (station === undefined) {
  634. throw new Meteor.Error(403, "Room doesn't exist.");
  635. } else {
  636. station.pauseRoom();
  637. }
  638. });
  639. } else {
  640. throw new Meteor.Error(403, "Invalid permissions.");
  641. }
  642. },
  643. resumeRoom: function(type) {
  644. if (isAdmin() && !isBanned()) {
  645. getStation(type, function(station) {
  646. if (station === undefined) {
  647. throw new Meteor.Error(403, "Room doesn't exist.");
  648. } else {
  649. station.resumeRoom();
  650. }
  651. });
  652. } else {
  653. throw new Meteor.Error(403, "Invalid permissions.");
  654. }
  655. },
  656. createUserMethod: function(formData, captchaData) {
  657. if (!isBanned()) {
  658. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  659. if (!verifyCaptchaResponse.success) {
  660. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  661. } else {
  662. Accounts.createUser({
  663. username: formData.username,
  664. email: formData.email,
  665. password: formData.password
  666. });
  667. }
  668. return true;
  669. }
  670. },
  671. addSongToQueue: function(type, songData) {
  672. if (Meteor.userId() && !isBanned()) {
  673. type = type.toLowerCase();
  674. if (Rooms.find({type: type}).count() === 1) {
  675. if (Queues.find({type: type}).count() === 0) {
  676. Queues.insert({type: type, songs: []});
  677. }
  678. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  679. songData.duration = getSongDuration(songData.title, songData.artist) || 0;
  680. songData.img = getSongAlbumArt(songData.title, songData.artist) || "";
  681. songData.skipDuration = 0;
  682. songData.likes = 0;
  683. songData.dislikes = 0;
  684. var mid = createUniqueSongId();
  685. if (mid !== undefined) {
  686. songData.mid = mid;
  687. Queues.update({type: type}, {
  688. $push: {
  689. songs: {
  690. id: songData.id,
  691. mid: songData.mid,
  692. title: songData.title,
  693. artist: songData.artist,
  694. duration: songData.duration,
  695. skipDuration: songData.skipDuration,
  696. likes: songData.likes,
  697. dislikes: songData.dislikes,
  698. img: songData.img,
  699. type: songData.type
  700. }
  701. }
  702. });
  703. return true;
  704. } else {
  705. throw new Meteor.Error(500, "Am error occured.");
  706. }
  707. } else {
  708. throw new Meteor.Error(403, "Invalid data.");
  709. }
  710. } else {
  711. throw new Meteor.Error(403, "Invalid genre.");
  712. }
  713. } else {
  714. throw new Meteor.Error(403, "Invalid permissions.");
  715. }
  716. },
  717. updateQueueSong: function(genre, oldSong, newSong) {
  718. if (isModerator() && !isBanned()) {
  719. newSong.mid = oldSong.mid;
  720. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  721. return true;
  722. } else {
  723. throw new Meteor.Error(403, "Invalid permissions.");
  724. }
  725. },
  726. updatePlaylistSong: function(genre, oldSong, newSong) {
  727. if (isModerator() && !isBanned()) {
  728. newSong.mid = oldSong.mid;
  729. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  730. return true;
  731. } else {
  732. throw new Meteor.Error(403, "Invalid permissions.");
  733. }
  734. },
  735. removeSongFromQueue: function(type, mid) {
  736. if (isModerator() && !isBanned()) {
  737. type = type.toLowerCase();
  738. Queues.update({type: type}, {$pull: {songs: {mid: mid}}});
  739. } else {
  740. throw new Meteor.Error(403, "Invalid permissions.");
  741. }
  742. },
  743. removeSongFromPlaylist: function(type, mid) {
  744. if (isModerator() && !isBanned()) {
  745. type = type.toLowerCase();
  746. var songs = Playlists.findOne({type: type}).songs;
  747. var song = undefined;
  748. songs.forEach(function(curr_song) {
  749. if (mid === curr_song.mid) {
  750. song = curr_song;
  751. return;
  752. }
  753. });
  754. Playlists.update({type: type}, {$pull: {songs: {mid: mid}}});
  755. if (song !== undefined) {
  756. song.deletedBy = Meteor.userId();
  757. song.deletedAt = new Date(Date.now());
  758. if (Deleted.find({type: type}).count() === 0) {
  759. Deleted.insert({type: type, songs: [song]});
  760. } else {
  761. Deleted.update({type: type}, {$push: {songs: song}});
  762. }
  763. }
  764. } else {
  765. throw new Meteor.Error(403, "Invalid permissions.");
  766. }
  767. },
  768. addSongToPlaylist: function(type, songData) {
  769. if (isModerator() && !isBanned()) {
  770. type = type.toLowerCase();
  771. if (Rooms.find({type: type}).count() === 1) {
  772. if (Playlists.find({type: type}).count() === 0) {
  773. Playlists.insert({type: type, songs: []});
  774. }
  775. var requiredProperties = ["type", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes"];
  776. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  777. for (var property in requiredProperties) {
  778. if (songData[requiredProperties[property]] === undefined) {
  779. throw new Meteor.Error(403, "Invalid data.");
  780. }
  781. }
  782. Playlists.update({type: type}, {
  783. $push: {
  784. songs: {
  785. id: songData.id,
  786. mid: songData.mid,
  787. title: songData.title,
  788. artist: songData.artist,
  789. duration: songData.duration,
  790. skipDuration: Number(songData.skipDuration),
  791. img: songData.img,
  792. type: songData.type,
  793. likes: Number(songData.likes),
  794. dislikes: Number(songData.dislikes)
  795. }
  796. }
  797. });
  798. Queues.update({type: type}, {$pull: {songs: {mid: songData.mid}}});
  799. return true;
  800. } else {
  801. throw new Meteor.Error(403, "Invalid data.");
  802. }
  803. } else {
  804. throw new Meteor.Error(403, "Invalid genre.");
  805. }
  806. } else {
  807. throw new Meteor.Error(403, "Invalid permissions.");
  808. }
  809. },
  810. createRoom: function(display, tag) {
  811. if (isAdmin() && !isBanned()) {
  812. createRoom(display, tag);
  813. } else {
  814. throw new Meteor.Error(403, "Invalid permissions.");
  815. }
  816. },
  817. deleteRoom: function(type){
  818. if (isAdmin() && !isBanned()) {
  819. Rooms.remove({type: type});
  820. Playlists.remove({type: type});
  821. Queues.remove({type: type});
  822. return true;
  823. } else {
  824. throw new Meteor.Error(403, "Invalid permissions.");
  825. }
  826. },
  827. getUserNum: function(){
  828. if (!isBanned()) {
  829. return Object.keys(Meteor.default_server.sessions).length;
  830. }
  831. }
  832. });
  833. Meteor.setInterval(function() {
  834. checkUsersPR();
  835. }, 10000);