server.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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, "punishments": 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("userProfiles", function(username) {
  362. var settings = Meteor.users.findOne({"profile.usernameL": username}, {fields: {"profile.settings": 1}});
  363. if (settings !== undefined && settings.profile.settings) {
  364. settings = settings.profile.settings;
  365. if (settings.showRating === true) {
  366. 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}});
  367. }
  368. }
  369. return Meteor.users.find({"profile.usernameL": username}, {fields: {"profile.username": 1, "profile.usernameL": 1, "profile.rank": 1, createdAt: 1, "profile.settings": 1}});
  370. });
  371. Meteor.publish("isAdmin", function() {
  372. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  373. });
  374. Meteor.publish("isModerator", function() {
  375. return Meteor.users.find({_id: this.userId, "profile.rank": "moderator"});
  376. });
  377. function isAdmin() {
  378. var userData = Meteor.users.find(Meteor.userId());
  379. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  380. return true;
  381. } else {
  382. return false;
  383. }
  384. }
  385. function isModerator() {
  386. var userData = Meteor.users.find(Meteor.userId());
  387. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  388. return true;
  389. } else {
  390. return isAdmin();
  391. }
  392. }
  393. function isBanned() {
  394. var userData = Meteor.users.findOne(Meteor.userId());
  395. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  396. var ban = userData.punishments.ban;
  397. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  398. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  399. return false;
  400. } else {
  401. return true;
  402. }
  403. } else {
  404. return false;
  405. }
  406. }
  407. Meteor.methods({
  408. banUser: function(username, period, reason) {
  409. if (isAdmin() && !isBanned()) {
  410. var user = Meteor.user();
  411. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  412. var bannedUntil = (new Date).getTime() + (period * 1000);
  413. if (bannedUntil > 8640000000000000) {
  414. bannedUntil = 8640000000000000;
  415. }
  416. bannedUntil = new Date(bannedUntil);
  417. var banObject = {bannedBy: user.profile.usernameL, bannedAt: new Date(Date.now()), bannedReason: reason, bannedUntil: bannedUntil};
  418. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  419. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  420. } else {
  421. throw new Meteor.Error(403, "Invalid permissions.");
  422. }
  423. },
  424. isBanned: function() {
  425. return isBanned();
  426. },
  427. updateSettings: function(showRating) {
  428. if (Meteor.userId() && !isBanned()) {
  429. var user = Meteor.user();
  430. if (showRating !== true && showRating !== false) {
  431. showRating = false;
  432. }
  433. if (user.profile.settings) {
  434. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  435. } else {
  436. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  437. }
  438. } else {
  439. throw new Meteor.Error(403, "Invalid permissions.");
  440. }
  441. },
  442. resetRating: function() {
  443. if (isAdmin() && !isBanned()) {
  444. stations.forEach(function (station) {
  445. var type = station.type;
  446. var temp_songs = Playlists.findOne({type: type}).songs;
  447. Playlists.update({type: type}, {$set: {"songs": []}});
  448. temp_songs.forEach(function (song) {
  449. song.likes = 0;
  450. song.dislikes = 0;
  451. Playlists.update({type: type}, {$push: {"songs": song}});
  452. });
  453. });
  454. Meteor.users.update({}, {$set: {"profile.liked": [], "profile.disliked": []}}, {multi: true});
  455. } else {
  456. throw Meteor.Error(403, "Invalid permissions.");
  457. }
  458. },
  459. removeAlerts: function() {
  460. if (isAdmin() && !isBanned()) {
  461. Alerts.update({active: true}, {$set: {active: false}}, { multi: true });
  462. } else {
  463. throw Meteor.Error(403, "Invalid permissions.");
  464. }
  465. },
  466. addAlert: function(description, priority) {
  467. if (isAdmin()) {
  468. if (description.length > 0 && description.length < 400) {
  469. var username = Meteor.user().profile.username;
  470. if (["danger", "warning", "success", "primary"].indexOf(priority) === -1) {
  471. priority = "warning";
  472. }
  473. Alerts.insert({description: description, priority: priority, active: true, createdBy: username});
  474. return true;
  475. } else {
  476. throw Meteor.Error(403, "Invalid description length.");
  477. }
  478. } else {
  479. throw Meteor.Error(403, "Invalid permissions.");
  480. }
  481. },
  482. sendMessage: function(type, message) {
  483. if (Meteor.userId() && !isBanned()) {
  484. var user = Meteor.user();
  485. var time = new Date();
  486. var rawrank = user.profile.rank;
  487. var username = user.profile.username;
  488. if (!message.replace(/\s/g, "").length > 0) {
  489. throw new Meteor.Error(406, "Message length cannot be 0.");
  490. }
  491. if (message.length > 300) {
  492. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  493. }
  494. else if (user.profile.rank === "admin") {
  495. Chat.insert({type: type, rawrank: rawrank, rank: "[A]", message: message, time: time, username: username});
  496. return true;
  497. }
  498. else if (user.profile.rank === "moderator") {
  499. Chat.insert({type: type, rawrank: rawrank, rank: "[M]", message: message, time: time, username: username});
  500. return true;
  501. }
  502. else {
  503. Chat.insert({type: type, rawrank: rawrank, message: message, time: time, username: username});
  504. return true;
  505. }
  506. } else {
  507. throw new Meteor.Error(403, "Invalid permissions.");
  508. }
  509. },
  510. likeSong: function(mid) {
  511. if (Meteor.userId() && !isBanned()) {
  512. var user = Meteor.user();
  513. if (user.profile.liked.indexOf(mid) === -1) {
  514. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  515. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": 1}})
  516. } else {
  517. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  518. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}})
  519. }
  520. if (user.profile.disliked.indexOf(mid) !== -1) {
  521. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  522. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}})
  523. }
  524. return true;
  525. } else {
  526. throw new Meteor.Error(403, "Invalid permissions.");
  527. }
  528. },
  529. dislikeSong: function(mid) {
  530. if (Meteor.userId() && !isBanned()) {
  531. var user = Meteor.user();
  532. if (user.profile.disliked.indexOf(mid) === -1) {
  533. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  534. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": 1}});
  535. } else {
  536. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  537. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}});
  538. }
  539. if (user.profile.liked.indexOf(mid) !== -1) {
  540. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  541. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}});
  542. }
  543. return true;
  544. } else {
  545. throw new Meteor.Error(403, "Invalid permissions.");
  546. }
  547. },
  548. voteSkip: function(type){
  549. if(Meteor.userId() && !isBanned()){
  550. var user = Meteor.user();
  551. getStation(type, function(station){
  552. if(station.voted.indexOf(user.profile.username) === -1){
  553. station.voted.push(user.profile.username);
  554. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  555. if(station.voted.length === 3){
  556. station.skipSong();
  557. }
  558. } else{
  559. throw new Meteor.Error(401, "Already voted.");
  560. }
  561. })
  562. }
  563. },
  564. submitReport: function(report, id) {
  565. if (!isBanned()) {
  566. var obj = report;
  567. obj.id = id;
  568. Reports.insert(obj);
  569. }
  570. },
  571. shufflePlaylist: function(type) {
  572. if (isAdmin() && !isBanned()) {
  573. getStation(type, function(station) {
  574. if (station === undefined) {
  575. throw new Meteor.Error(404, "Station not found.");
  576. } else {
  577. station.cancelTimer();
  578. station.shufflePlaylist();
  579. }
  580. });
  581. }
  582. },
  583. skipSong: function(type) {
  584. if (isAdmin() && !isBanned()) {
  585. getStation(type, function(station) {
  586. if (station === undefined) {
  587. throw new Meteor.Error(404, "Station not found.");
  588. } else {
  589. station.skipSong();
  590. }
  591. });
  592. }
  593. },
  594. pauseRoom: function(type) {
  595. if (isAdmin() && !isBanned()) {
  596. getStation(type, function(station) {
  597. if (station === undefined) {
  598. throw new Meteor.Error(403, "Room doesn't exist.");
  599. } else {
  600. station.pauseRoom();
  601. }
  602. });
  603. } else {
  604. throw new Meteor.Error(403, "Invalid permissions.");
  605. }
  606. },
  607. resumeRoom: function(type) {
  608. if (isAdmin() && !isBanned()) {
  609. getStation(type, function(station) {
  610. if (station === undefined) {
  611. throw new Meteor.Error(403, "Room doesn't exist.");
  612. } else {
  613. station.resumeRoom();
  614. }
  615. });
  616. } else {
  617. throw new Meteor.Error(403, "Invalid permissions.");
  618. }
  619. },
  620. createUserMethod: function(formData, captchaData) {
  621. if (!isBanned()) {
  622. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  623. if (!verifyCaptchaResponse.success) {
  624. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  625. } else {
  626. Accounts.createUser({
  627. username: formData.username,
  628. email: formData.email,
  629. password: formData.password
  630. });
  631. }
  632. return true;
  633. }
  634. },
  635. addSongToQueue: function(type, songData) {
  636. if (Meteor.userId() && !isBanned()) {
  637. type = type.toLowerCase();
  638. if (Rooms.find({type: type}).count() === 1) {
  639. if (Queues.find({type: type}).count() === 0) {
  640. Queues.insert({type: type, songs: []});
  641. }
  642. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  643. songData.duration = getSongDuration(songData.title, songData.artist) || 0;
  644. songData.img = getSongAlbumArt(songData.title, songData.artist) || "";
  645. songData.skipDuration = 0;
  646. songData.likes = 0;
  647. songData.dislikes = 0;
  648. var mid = createUniqueSongId();
  649. if (mid !== undefined) {
  650. songData.mid = mid;
  651. Queues.update({type: type}, {
  652. $push: {
  653. songs: {
  654. id: songData.id,
  655. mid: songData.mid,
  656. title: songData.title,
  657. artist: songData.artist,
  658. duration: songData.duration,
  659. skipDuration: songData.skipDuration,
  660. likes: songData.likes,
  661. dislikes: songData.dislikes,
  662. img: songData.img,
  663. type: songData.type
  664. }
  665. }
  666. });
  667. return true;
  668. } else {
  669. throw new Meteor.Error(500, "Am error occured.");
  670. }
  671. } else {
  672. throw new Meteor.Error(403, "Invalid data.");
  673. }
  674. } else {
  675. throw new Meteor.Error(403, "Invalid genre.");
  676. }
  677. } else {
  678. throw new Meteor.Error(403, "Invalid permissions.");
  679. }
  680. },
  681. updateQueueSong: function(genre, oldSong, newSong) {
  682. if (isModerator() && !isBanned()) {
  683. newSong.mid = oldSong.mid;
  684. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  685. return true;
  686. } else {
  687. throw new Meteor.Error(403, "Invalid permissions.");
  688. }
  689. },
  690. updatePlaylistSong: function(genre, oldSong, newSong) {
  691. if (isModerator() && !isBanned()) {
  692. newSong.mid = oldSong.mid;
  693. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  694. return true;
  695. } else {
  696. throw new Meteor.Error(403, "Invalid permissions.");
  697. }
  698. },
  699. removeSongFromQueue: function(type, mid) {
  700. if (isModerator() && !isBanned()) {
  701. type = type.toLowerCase();
  702. Queues.update({type: type}, {$pull: {songs: {mid: mid}}});
  703. } else {
  704. throw new Meteor.Error(403, "Invalid permissions.");
  705. }
  706. },
  707. removeSongFromPlaylist: function(type, mid) {
  708. if (isModerator() && !isBanned()) {
  709. type = type.toLowerCase();
  710. var songs = Playlists.findOne({type: type}).songs;
  711. var song = undefined;
  712. songs.forEach(function(curr_song) {
  713. if (mid === curr_song.mid) {
  714. song = curr_song;
  715. return;
  716. }
  717. });
  718. Playlists.update({type: type}, {$pull: {songs: {mid: mid}}});
  719. if (song !== undefined) {
  720. song.deletedBy = Meteor.userId();
  721. song.deletedAt = new Date(Date.now());
  722. if (Deleted.find({type: type}).count() === 0) {
  723. Deleted.insert({type: type, songs: [song]});
  724. } else {
  725. Deleted.update({type: type}, {$push: {songs: song}});
  726. }
  727. }
  728. } else {
  729. throw new Meteor.Error(403, "Invalid permissions.");
  730. }
  731. },
  732. addSongToPlaylist: function(type, songData) {
  733. if (isModerator() && !isBanned()) {
  734. type = type.toLowerCase();
  735. if (Rooms.find({type: type}).count() === 1) {
  736. if (Playlists.find({type: type}).count() === 0) {
  737. Playlists.insert({type: type, songs: []});
  738. }
  739. var requiredProperties = ["type", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes"];
  740. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  741. for (var property in requiredProperties) {
  742. if (songData[requiredProperties[property]] === undefined) {
  743. throw new Meteor.Error(403, "Invalid data.");
  744. }
  745. }
  746. Playlists.update({type: type}, {
  747. $push: {
  748. songs: {
  749. id: songData.id,
  750. mid: songData.mid,
  751. title: songData.title,
  752. artist: songData.artist,
  753. duration: songData.duration,
  754. skipDuration: Number(songData.skipDuration),
  755. img: songData.img,
  756. type: songData.type,
  757. likes: Number(songData.likes),
  758. dislikes: Number(songData.dislikes)
  759. }
  760. }
  761. });
  762. Queues.update({type: type}, {$pull: {songs: {mid: songData.mid}}});
  763. return true;
  764. } else {
  765. throw new Meteor.Error(403, "Invalid data.");
  766. }
  767. } else {
  768. throw new Meteor.Error(403, "Invalid genre.");
  769. }
  770. } else {
  771. throw new Meteor.Error(403, "Invalid permissions.");
  772. }
  773. },
  774. createRoom: function(display, tag) {
  775. if (isAdmin() && !isBanned()) {
  776. createRoom(display, tag);
  777. } else {
  778. throw new Meteor.Error(403, "Invalid permissions.");
  779. }
  780. },
  781. deleteRoom: function(type){
  782. if (isAdmin() && !isBanned()) {
  783. Rooms.remove({type: type});
  784. Playlists.remove({type: type});
  785. Queues.remove({type: type});
  786. return true;
  787. } else {
  788. throw new Meteor.Error(403, "Invalid permissions.");
  789. }
  790. },
  791. getUserNum: function(){
  792. if (!isBanned()) {
  793. return Object.keys(Meteor.default_server.sessions).length;
  794. }
  795. }
  796. });
  797. Meteor.setInterval(function() {
  798. checkUsersPR();
  799. }, 10000);