server.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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 _this = 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. _this.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. _this.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. _this.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. this.songTimer();
  206. this.voted = [];
  207. }
  208. function shuffle(array) {
  209. var currentIndex = array.length, temporaryValue, randomIndex ;
  210. // While there remain elements to shuffle...
  211. while (0 !== currentIndex) {
  212. // Pick a remaining element...
  213. randomIndex = Math.floor(Math.random() * currentIndex);
  214. currentIndex -= 1;
  215. // And swap it with the current element.
  216. temporaryValue = array[currentIndex];
  217. array[currentIndex] = array[randomIndex];
  218. array[randomIndex] = temporaryValue;
  219. }
  220. return array;
  221. }
  222. function Timer(callback, delay) {
  223. var timerId, start, remaining = delay;
  224. var timeWhenPaused = 0;
  225. var timePaused = new Date();
  226. this.pause = function() {
  227. Meteor.clearTimeout(timerId);
  228. remaining -= new Date() - start;
  229. timePaused = new Date();
  230. };
  231. this.resume = function() {
  232. start = new Date();
  233. Meteor.clearTimeout(timerId);
  234. timerId = Meteor.setTimeout(callback, remaining);
  235. timeWhenPaused += new Date() - timePaused;
  236. };
  237. this.timeWhenPaused = function() {
  238. return timeWhenPaused;
  239. };
  240. this.resume();
  241. }
  242. Meteor.users.deny({update: function () { return true; }});
  243. Meteor.users.deny({insert: function () { return true; }});
  244. Meteor.users.deny({remove: function () { return true; }});
  245. function getSongDuration(query, artistName){
  246. var duration;
  247. var search = query;
  248. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  249. for(var i in res.data){
  250. for(var j in res.data[i].items){
  251. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  252. duration = res.data[i].items[j].duration_ms / 1000;
  253. return duration;
  254. }
  255. }
  256. }
  257. }
  258. function getSongAlbumArt(query, artistName){
  259. var albumart;
  260. var search = query;
  261. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  262. for(var i in res.data){
  263. for(var j in res.data[i].items){
  264. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  265. albumart = res.data[i].items[j].album.images[1].url
  266. return albumart;
  267. }
  268. }
  269. }
  270. }
  271. //var room_types = ["edm", "nightcore"];
  272. var songsArr = [];
  273. function getSongsByType(type) {
  274. if (type === "edm") {
  275. return [
  276. {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"},
  277. {id: "aHjpOzsQ9YI", mid: "goG88g", title: "Crystallize", artist: "Lindsey Stirling", duration: getSongDuration("Crystallize", "Lindsey Stirling"), type: "YouTube", img: "https://i.scdn.co/image/b0c1ccdd0cd7bcda741ccc1c3e036f4ed2e52312"}
  278. ];
  279. } else if (type === "nightcore") {
  280. 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"}];
  281. } else {
  282. 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"}];
  283. }
  284. }
  285. Rooms.find({}).fetch().forEach(function(room) {
  286. var type = room.type;
  287. if (Playlists.find({type: type}).count() === 0) {
  288. if (type === "edm") {
  289. Playlists.insert({type: type, songs: getSongsByType(type)});
  290. } else if (type === "nightcore") {
  291. Playlists.insert({type: type, songs: getSongsByType(type)});
  292. } else {
  293. Playlists.insert({type: type, songs: getSongsByType(type)});
  294. }
  295. }
  296. if (Playlists.findOne({type: type}).songs.length === 0) {
  297. // Add a global video to Playlist so it can proceed
  298. } else {
  299. stations.push(new Station(type));
  300. }
  301. });
  302. Accounts.validateNewUser(function(user) {
  303. var username;
  304. if (user.services) {
  305. if (user.services.github) {
  306. username = user.services.github.username;
  307. } else if (user.services.facebook) {
  308. username = user.services.facebook.first_name;
  309. } else if (user.services.password) {
  310. username = user.username;
  311. }
  312. }
  313. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() !== 0) {
  314. throw new Meteor.Error(403, "An account with that username already exists.");
  315. } else {
  316. return true;
  317. }
  318. });
  319. Accounts.onCreateUser(function(options, user) {
  320. var username;
  321. if (user.services) {
  322. if (user.services.github) {
  323. username = user.services.github.username;
  324. } else if (user.services.facebook) {
  325. username = user.services.facebook.first_name;
  326. } else if (user.services.password) {
  327. username = user.username;
  328. }
  329. }
  330. user.profile = {username: username, usernameL: username.toLowerCase(), rank: "default", liked: [], disliked: [], settings: {showRating: false}};
  331. return user;
  332. });
  333. Meteor.publish("alerts", function() {
  334. return Alerts.find({active: true})
  335. });
  336. Meteor.publish("userData", function(userId) {
  337. if (userId !== undefined) {
  338. return Meteor.users.find(userId, {fields: {"services.github.username": 1}})
  339. } else {
  340. return undefined;
  341. }
  342. });
  343. Meteor.publish("allAlerts", function() {
  344. return Alerts.find({active: false})
  345. });
  346. Meteor.publish("playlists", function() {
  347. return Playlists.find({})
  348. });
  349. Meteor.publish("rooms", function() {
  350. return Rooms.find({});
  351. });
  352. Meteor.publish("queues", function() {
  353. return Queues.find({});
  354. });
  355. Meteor.publish("reports", function() {
  356. return Reports.find({});
  357. });
  358. Meteor.publish("chat", function() {
  359. return Chat.find({});
  360. });
  361. Meteor.publish("ownBan", function(userId) {
  362. return Meteor.users.find(userId, {"punishments.ban": 1, "profile": 1});
  363. });
  364. Meteor.publish("userProfiles", function(username) {
  365. var settings = Meteor.users.findOne({"profile.usernameL": username}, {fields: {"profile.settings": 1}});
  366. if (settings !== undefined && settings.profile.settings) {
  367. settings = settings.profile.settings;
  368. if (settings.showRating === true) {
  369. 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}});
  370. }
  371. }
  372. return Meteor.users.find({"profile.usernameL": username}, {fields: {"profile.username": 1, "profile.usernameL": 1, "profile.rank": 1, createdAt: 1, "profile.settings": 1}});
  373. });
  374. Meteor.publish("isAdmin", function() {
  375. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  376. });
  377. Meteor.publish("isModerator", function() {
  378. return Meteor.users.find({_id: this.userId, "profile.rank": "moderator"});
  379. });
  380. function isAdmin() {
  381. var userData = Meteor.users.find(Meteor.userId());
  382. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  383. return true;
  384. } else {
  385. return false;
  386. }
  387. }
  388. function isModerator() {
  389. var userData = Meteor.users.find(Meteor.userId());
  390. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  391. return true;
  392. } else {
  393. return isAdmin();
  394. }
  395. }
  396. function isBanned() {
  397. var userData = Meteor.users.findOne(Meteor.userId());
  398. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  399. var ban = userData.punishments.ban;
  400. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  401. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  402. return false;
  403. } else {
  404. return true;
  405. }
  406. } else {
  407. return false;
  408. }
  409. }
  410. Meteor.methods({
  411. banUser: function(username, period, reason) {
  412. if (isAdmin() && !isBanned()) {
  413. var user = Meteor.user();
  414. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  415. var bannedUntil = (new Date).getTime() + (period * 1000);
  416. if (bannedUntil > 8640000000000000) {
  417. bannedUntil = 8640000000000000;
  418. }
  419. bannedUntil = new Date(bannedUntil);
  420. var banObject = {bannedBy: user.profile.usernameL, bannedAt: new Date(Date.now()), bannedReason: reason, bannedUntil: bannedUntil};
  421. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  422. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  423. } else {
  424. throw new Meteor.Error(403, "Invalid permissions.");
  425. }
  426. },
  427. isBanned: function() {
  428. return isBanned();
  429. },
  430. updateSettings: function(showRating) {
  431. if (Meteor.userId() && !isBanned()) {
  432. var user = Meteor.user();
  433. if (showRating !== true && showRating !== false) {
  434. showRating = false;
  435. }
  436. if (user.profile.settings) {
  437. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  438. } else {
  439. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  440. }
  441. } else {
  442. throw new Meteor.Error(403, "Invalid permissions.");
  443. }
  444. },
  445. resetRating: function() {
  446. if (isAdmin() && !isBanned()) {
  447. stations.forEach(function (station) {
  448. var type = station.type;
  449. var temp_songs = Playlists.findOne({type: type}).songs;
  450. Playlists.update({type: type}, {$set: {"songs": []}});
  451. temp_songs.forEach(function (song) {
  452. song.likes = 0;
  453. song.dislikes = 0;
  454. Playlists.update({type: type}, {$push: {"songs": song}});
  455. });
  456. });
  457. Meteor.users.update({}, {$set: {"profile.liked": [], "profile.disliked": []}}, {multi: true});
  458. } else {
  459. throw Meteor.Error(403, "Invalid permissions.");
  460. }
  461. },
  462. removeAlerts: function() {
  463. if (isAdmin() && !isBanned()) {
  464. Alerts.update({active: true}, {$set: {active: false}}, { multi: true });
  465. } else {
  466. throw Meteor.Error(403, "Invalid permissions.");
  467. }
  468. },
  469. addAlert: function(description, priority) {
  470. if (isAdmin()) {
  471. if (description.length > 0 && description.length < 400) {
  472. var username = Meteor.user().profile.username;
  473. if (["danger", "warning", "success", "primary"].indexOf(priority) === -1) {
  474. priority = "warning";
  475. }
  476. Alerts.insert({description: description, priority: priority, active: true, createdBy: username});
  477. return true;
  478. } else {
  479. throw Meteor.Error(403, "Invalid description length.");
  480. }
  481. } else {
  482. throw Meteor.Error(403, "Invalid permissions.");
  483. }
  484. },
  485. sendMessage: function(type, message) {
  486. if (Meteor.userId() && !isBanned()) {
  487. var user = Meteor.user();
  488. var time = new Date();
  489. var rawrank = user.profile.rank;
  490. var username = user.profile.username;
  491. if (!message.replace(/\s/g, "").length > 0) {
  492. throw new Meteor.Error(406, "Message length cannot be 0.");
  493. }
  494. if (message.length > 300) {
  495. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  496. }
  497. else if (user.profile.rank === "admin") {
  498. Chat.insert({type: type, rawrank: rawrank, rank: "[A]", message: message, time: time, username: username});
  499. return true;
  500. }
  501. else if (user.profile.rank === "moderator") {
  502. Chat.insert({type: type, rawrank: rawrank, rank: "[M]", message: message, time: time, username: username});
  503. return true;
  504. }
  505. else {
  506. Chat.insert({type: type, rawrank: rawrank, message: message, time: time, username: username});
  507. return true;
  508. }
  509. } else {
  510. throw new Meteor.Error(403, "Invalid permissions.");
  511. }
  512. },
  513. likeSong: function(mid) {
  514. if (Meteor.userId() && !isBanned()) {
  515. var user = Meteor.user();
  516. if (user.profile.liked.indexOf(mid) === -1) {
  517. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  518. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": 1}})
  519. } else {
  520. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  521. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}})
  522. }
  523. if (user.profile.disliked.indexOf(mid) !== -1) {
  524. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  525. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}})
  526. }
  527. return true;
  528. } else {
  529. throw new Meteor.Error(403, "Invalid permissions.");
  530. }
  531. },
  532. dislikeSong: function(mid) {
  533. if (Meteor.userId() && !isBanned()) {
  534. var user = Meteor.user();
  535. if (user.profile.disliked.indexOf(mid) === -1) {
  536. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  537. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": 1}});
  538. } else {
  539. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  540. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}});
  541. }
  542. if (user.profile.liked.indexOf(mid) !== -1) {
  543. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  544. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}});
  545. }
  546. return true;
  547. } else {
  548. throw new Meteor.Error(403, "Invalid permissions.");
  549. }
  550. },
  551. voteSkip: function(type){
  552. if(Meteor.userId() && !isBanned()){
  553. var user = Meteor.user();
  554. getStation(type, function(station){
  555. if(station.voted.indexOf(user.profile.username) === -1){
  556. station.voted.push(user.profile.username);
  557. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  558. if(station.voted.length === 3){
  559. station.skipSong();
  560. }
  561. } else{
  562. throw new Meteor.Error(401, "Already voted.");
  563. }
  564. })
  565. }
  566. },
  567. submitReport: function(report, id) {
  568. if (!isBanned()) {
  569. var obj = report;
  570. obj.id = id;
  571. Reports.insert(obj);
  572. }
  573. },
  574. shufflePlaylist: function(type) {
  575. if (isAdmin() && !isBanned()) {
  576. getStation(type, function(station) {
  577. if (station === undefined) {
  578. throw new Meteor.Error(404, "Station not found.");
  579. } else {
  580. station.cancelTimer();
  581. station.shufflePlaylist();
  582. }
  583. });
  584. }
  585. },
  586. skipSong: function(type) {
  587. if (isAdmin() && !isBanned()) {
  588. getStation(type, function(station) {
  589. if (station === undefined) {
  590. throw new Meteor.Error(404, "Station not found.");
  591. } else {
  592. station.skipSong();
  593. }
  594. });
  595. }
  596. },
  597. pauseRoom: function(type) {
  598. if (isAdmin() && !isBanned()) {
  599. getStation(type, function(station) {
  600. if (station === undefined) {
  601. throw new Meteor.Error(403, "Room doesn't exist.");
  602. } else {
  603. station.pauseRoom();
  604. }
  605. });
  606. } else {
  607. throw new Meteor.Error(403, "Invalid permissions.");
  608. }
  609. },
  610. resumeRoom: function(type) {
  611. if (isAdmin() && !isBanned()) {
  612. getStation(type, function(station) {
  613. if (station === undefined) {
  614. throw new Meteor.Error(403, "Room doesn't exist.");
  615. } else {
  616. station.resumeRoom();
  617. }
  618. });
  619. } else {
  620. throw new Meteor.Error(403, "Invalid permissions.");
  621. }
  622. },
  623. createUserMethod: function(formData, captchaData) {
  624. if (!isBanned()) {
  625. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  626. if (!verifyCaptchaResponse.success) {
  627. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  628. } else {
  629. Accounts.createUser({
  630. username: formData.username,
  631. email: formData.email,
  632. password: formData.password
  633. });
  634. }
  635. return true;
  636. }
  637. },
  638. addSongToQueue: function(type, songData) {
  639. if (Meteor.userId() && !isBanned()) {
  640. type = type.toLowerCase();
  641. if (Rooms.find({type: type}).count() === 1) {
  642. if (Queues.find({type: type}).count() === 0) {
  643. Queues.insert({type: type, songs: []});
  644. }
  645. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  646. songData.duration = getSongDuration(songData.title, songData.artist) || 0;
  647. songData.img = getSongAlbumArt(songData.title, songData.artist) || "";
  648. songData.skipDuration = 0;
  649. songData.likes = 0;
  650. songData.dislikes = 0;
  651. var mid = createUniqueSongId();
  652. if (mid !== undefined) {
  653. songData.mid = mid;
  654. Queues.update({type: type}, {
  655. $push: {
  656. songs: {
  657. id: songData.id,
  658. mid: songData.mid,
  659. title: songData.title,
  660. artist: songData.artist,
  661. duration: songData.duration,
  662. skipDuration: songData.skipDuration,
  663. likes: songData.likes,
  664. dislikes: songData.dislikes,
  665. img: songData.img,
  666. type: songData.type
  667. }
  668. }
  669. });
  670. return true;
  671. } else {
  672. throw new Meteor.Error(500, "Am error occured.");
  673. }
  674. } else {
  675. throw new Meteor.Error(403, "Invalid data.");
  676. }
  677. } else {
  678. throw new Meteor.Error(403, "Invalid genre.");
  679. }
  680. } else {
  681. throw new Meteor.Error(403, "Invalid permissions.");
  682. }
  683. },
  684. updateQueueSong: function(genre, oldSong, newSong) {
  685. if (isModerator() && !isBanned()) {
  686. newSong.mid = oldSong.mid;
  687. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  688. return true;
  689. } else {
  690. throw new Meteor.Error(403, "Invalid permissions.");
  691. }
  692. },
  693. updatePlaylistSong: function(genre, oldSong, newSong) {
  694. if (isModerator() && !isBanned()) {
  695. newSong.mid = oldSong.mid;
  696. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  697. return true;
  698. } else {
  699. throw new Meteor.Error(403, "Invalid permissions.");
  700. }
  701. },
  702. removeSongFromQueue: function(type, mid) {
  703. if (isModerator() && !isBanned()) {
  704. type = type.toLowerCase();
  705. Queues.update({type: type}, {$pull: {songs: {mid: mid}}});
  706. } else {
  707. throw new Meteor.Error(403, "Invalid permissions.");
  708. }
  709. },
  710. removeSongFromPlaylist: function(type, mid) {
  711. if (isModerator() && !isBanned()) {
  712. type = type.toLowerCase();
  713. var songs = Playlists.findOne({type: type}).songs;
  714. var song = undefined;
  715. songs.forEach(function(curr_song) {
  716. if (mid === curr_song.mid) {
  717. song = curr_song;
  718. return;
  719. }
  720. });
  721. Playlists.update({type: type}, {$pull: {songs: {mid: mid}}});
  722. if (song !== undefined) {
  723. song.deletedBy = Meteor.userId();
  724. song.deletedAt = new Date(Date.now());
  725. if (Deleted.find({type: type}).count() === 0) {
  726. Deleted.insert({type: type, songs: [song]});
  727. } else {
  728. Deleted.update({type: type}, {$push: {songs: song}});
  729. }
  730. }
  731. } else {
  732. throw new Meteor.Error(403, "Invalid permissions.");
  733. }
  734. },
  735. addSongToPlaylist: function(type, songData) {
  736. if (isModerator() && !isBanned()) {
  737. type = type.toLowerCase();
  738. if (Rooms.find({type: type}).count() === 1) {
  739. if (Playlists.find({type: type}).count() === 0) {
  740. Playlists.insert({type: type, songs: []});
  741. }
  742. var requiredProperties = ["type", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes"];
  743. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  744. for (var property in requiredProperties) {
  745. if (songData[requiredProperties[property]] === undefined) {
  746. throw new Meteor.Error(403, "Invalid data.");
  747. }
  748. }
  749. Playlists.update({type: type}, {
  750. $push: {
  751. songs: {
  752. id: songData.id,
  753. mid: songData.mid,
  754. title: songData.title,
  755. artist: songData.artist,
  756. duration: songData.duration,
  757. skipDuration: Number(songData.skipDuration),
  758. img: songData.img,
  759. type: songData.type,
  760. likes: Number(songData.likes),
  761. dislikes: Number(songData.dislikes)
  762. }
  763. }
  764. });
  765. Queues.update({type: type}, {$pull: {songs: {mid: songData.mid}}});
  766. return true;
  767. } else {
  768. throw new Meteor.Error(403, "Invalid data.");
  769. }
  770. } else {
  771. throw new Meteor.Error(403, "Invalid genre.");
  772. }
  773. } else {
  774. throw new Meteor.Error(403, "Invalid permissions.");
  775. }
  776. },
  777. createRoom: function(display, tag) {
  778. if (isAdmin() && !isBanned()) {
  779. createRoom(display, tag);
  780. } else {
  781. throw new Meteor.Error(403, "Invalid permissions.");
  782. }
  783. },
  784. deleteRoom: function(type){
  785. if (isAdmin() && !isBanned()) {
  786. Rooms.remove({type: type});
  787. Playlists.remove({type: type});
  788. Queues.remove({type: type});
  789. return true;
  790. } else {
  791. throw new Meteor.Error(403, "Invalid permissions.");
  792. }
  793. },
  794. getUserNum: function(){
  795. if (!isBanned()) {
  796. return Object.keys(Meteor.default_server.sessions).length;
  797. }
  798. }
  799. });
  800. Meteor.setInterval(function() {
  801. checkUsersPR();
  802. }, 10000);