server.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  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, false);
  17. }
  18. }
  19. emojione.ascii = true;
  20. Accounts.config({
  21. sendVerificationEmail: true
  22. });
  23. if (Songs.find().count() === 0) {
  24. Songs.insert(default_song);
  25. }
  26. });
  27. var default_song = {
  28. id: "xKVcVSYmesU",
  29. mid: "ABCDEF",
  30. likes: 0,
  31. dislikes: 0,
  32. title: "Immortals",
  33. artist: "Fall Out Boy",
  34. img: "http://c.directlyrics.com/img/upload/fall-out-boy-sixth-album-cover.jpg",
  35. type: "YouTube",
  36. duration: 181,
  37. skipDuration: 0,
  38. requestedBy: "NONE",
  39. approvedBy: "NONE",
  40. genres: []
  41. };
  42. Alerts.update({active: true}, {$set: {active: false}}, {multi: true});
  43. var stations = [];
  44. var voteNum = 0;
  45. var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
  46. function createUniqueSongId() {
  47. var code = "";
  48. for (var i = 0; i < 6; i++) {
  49. code += chars[Math.floor(Math.random() * chars.length)];
  50. }
  51. if (Playlists.find({"songs.mid": code}).count() > 0) {
  52. return createUniqueSongId();
  53. } else {
  54. return code;
  55. }
  56. }
  57. function checkUsersPR() {
  58. var output = {};
  59. var connections = Meteor.server.stream_server.open_sockets;
  60. _.each(connections, function (connection) {
  61. // named subscriptions
  62. if (connection._meteorSession !== undefined && connection._meteorSession !== null) {
  63. var subs = connection._meteorSession._namedSubs;
  64. //var ip = connection.remoteAddress;
  65. var used_subs = [];
  66. for (var sub in subs) {
  67. var mySubName = subs[sub]._name;
  68. if (subs[sub]._params.length > 0) {
  69. mySubName += subs[sub]._params[0]; // assume one id parameter for now
  70. }
  71. if (used_subs.indexOf(mySubName) === -1) {
  72. used_subs.push(mySubName);
  73. if (!output[mySubName]) {
  74. output[mySubName] = 1;
  75. } else {
  76. output[mySubName] += 1;
  77. }
  78. }
  79. }
  80. }
  81. // there are also these 'universal subscriptions'
  82. //not sure what these are, i count none in my tests
  83. //var usubs = connection._meteorSession._universalSubs;
  84. });
  85. var emptyStations = [];
  86. stations.forEach(function (station) {
  87. emptyStations.push(station);
  88. });
  89. for (var key in output) {
  90. getStation(key, function (station) {
  91. emptyStations.splice(emptyStations.indexOf(station), 1);
  92. Rooms.update({type: key}, {$set: {users: output[key]}});
  93. });
  94. }
  95. emptyStations.forEach(function (emptyStation) {
  96. Rooms.update({type: emptyStation.type}, {$set: {users: 0}});
  97. });
  98. return output;
  99. }
  100. function getStation(type, cb) {
  101. stations.forEach(function (station) {
  102. if (station.type === type) {
  103. cb(station);
  104. return;
  105. }
  106. });
  107. }
  108. function createRoom(display, tag, private) {
  109. var type = tag;
  110. if (Rooms.find({type: type}).count() === 0) {
  111. Rooms.insert({
  112. display: display,
  113. type: type,
  114. users: 0,
  115. private: private,
  116. roomDesc: "Test room yo",
  117. currentSong: {song: default_song, started: 0}
  118. }, function (err) {
  119. if (err) {
  120. throw err;
  121. } else {
  122. stations.push(new Station(type));
  123. }
  124. });
  125. } else {
  126. return "Room already exists";
  127. }
  128. }
  129. function Station(type) {
  130. if (Playlists.find({type: type}).count() === 0) {
  131. Playlists.insert({type: type, songs: [default_song.mid], lastSong: 0});
  132. }
  133. if (Songs.find({genres: type}).count() > 0) {
  134. var list = Songs.find({genres: type}).fetch();
  135. list.forEach(function(song){
  136. if (Playlists.findOne({type: type, songs: song.mid}) === undefined) {
  137. Playlists.update({type: type}, {$push: {songs: song.mid}});
  138. }
  139. });
  140. }
  141. if (Playlists.findOne({type: type}).songs.length === 0) {
  142. Playlists.update({type: type}, {$push: {songs: default_song.mid}});
  143. }
  144. Meteor.publish(type, function () {
  145. return undefined;
  146. });
  147. var self = this;
  148. var startedAt = Date.now();
  149. var playlist = Playlists.findOne({type: type});
  150. var songs = playlist.songs;
  151. var currentSong = playlist.lastSong;
  152. if (currentSong < (songs.length - 1)) {
  153. currentSong++;
  154. } else currentSong = 0;
  155. var currentMid = songs[currentSong];
  156. var res = Rooms.update({type: type}, {
  157. $set: {
  158. currentSong: {song: Songs.findOne({mid: songs[currentSong]}), started: startedAt},
  159. users: 0
  160. }
  161. });
  162. console.log(res);
  163. this.skipSong = function () {
  164. self.voted = [];
  165. voteNum = 0;
  166. Rooms.update({type: type}, {$set: {votes: 0}});
  167. songs = Playlists.findOne({type: type}).songs;
  168. songs.forEach(function (mid, index) {
  169. if (mid === currentMid) {
  170. currentSong = index;
  171. }
  172. });
  173. if (currentSong < (songs.length - 1)) {
  174. currentSong++;
  175. } else currentSong = 0;
  176. if (songs);
  177. if (currentSong === 0) {
  178. this.shufflePlaylist();
  179. } else {
  180. currentMid = songs[currentSong];
  181. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  182. Rooms.update({type: type}, {$set: {timePaused: 0}});
  183. this.songTimer();
  184. Rooms.update({type: type}, {$set: {currentSong: {song: Songs.findOne({mid: songs[currentSong]}), started: startedAt}}});
  185. }
  186. };
  187. this.shufflePlaylist = function () {
  188. voteNum = 0;
  189. Rooms.update({type: type}, {$set: {votes: 0}});
  190. self.voted = [];
  191. songs = Playlists.findOne({type: type}).songs;
  192. currentSong = 0;
  193. Playlists.update({type: type}, {$set: {"songs": []}});
  194. songs = shuffle(songs);
  195. songs.forEach(function (song) {
  196. Playlists.update({type: type}, {$push: {"songs": song}});
  197. });
  198. currentMid = songs[currentSong];
  199. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  200. Rooms.update({type: type}, {$set: {timePaused: 0}});
  201. this.songTimer();
  202. Rooms.update({type: type}, {$set: {currentSong: {song: Songs.findOne({mid: songs[currentSong]}), started: startedAt}}});
  203. };
  204. Rooms.update({type: type}, {$set: {timePaused: 0}});
  205. var timer;
  206. this.songTimer = function () {
  207. startedAt = Date.now();
  208. if (timer !== undefined) {
  209. timer.pause();
  210. }
  211. timer = new Timer(function () {
  212. self.skipSong();
  213. }, Songs.findOne({mid: songs[currentSong]}).duration * 1000);
  214. };
  215. var state = Rooms.findOne({type: type}).state;
  216. this.pauseRoom = function () {
  217. if (state !== "paused") {
  218. timer.pause();
  219. Rooms.update({type: type}, {$set: {state: "paused"}});
  220. state = "paused";
  221. }
  222. };
  223. this.resumeRoom = function () {
  224. if (state !== "playing") {
  225. timer.resume();
  226. Rooms.update({type: type}, {$set: {state: "playing", timePaused: timer.timeWhenPaused()}});
  227. state = "playing";
  228. }
  229. };
  230. this.cancelTimer = function () {
  231. timer.pause();
  232. };
  233. this.getState = function () {
  234. return state;
  235. };
  236. this.type = type;
  237. var private = Rooms.findOne({type: type}).private;
  238. if (typeof private !== "boolean") {
  239. Rooms.update({type: type}, {$set: {"private": false}});
  240. private = false;
  241. }
  242. this.private = private;
  243. this.unlock = function () {
  244. if (self.private) {
  245. self.private = false;
  246. Rooms.update({type: type}, {$set: {"private": false}});
  247. }
  248. };
  249. this.lock = function () {
  250. if (!self.private) {
  251. self.private = true;
  252. Rooms.update({type: type}, {$set: {"private": true}});
  253. }
  254. };
  255. this.songTimer();
  256. this.voted = [];
  257. }
  258. function shuffle(array) {
  259. var currentIndex = array.length, temporaryValue, randomIndex;
  260. // While there remain elements to shuffle...
  261. while (0 !== currentIndex) {
  262. // Pick a remaining element...
  263. randomIndex = Math.floor(Math.random() * currentIndex);
  264. currentIndex -= 1;
  265. // And swap it with the current element.
  266. temporaryValue = array[currentIndex];
  267. array[currentIndex] = array[randomIndex];
  268. array[randomIndex] = temporaryValue;
  269. }
  270. return array;
  271. }
  272. function Timer(callback, delay) {
  273. var timerId, start, remaining = delay;
  274. var timeWhenPaused = 0;
  275. var timePaused = new Date();
  276. this.pause = function () {
  277. Meteor.clearTimeout(timerId);
  278. remaining -= new Date() - start;
  279. timePaused = new Date();
  280. };
  281. this.resume = function () {
  282. start = new Date();
  283. Meteor.clearTimeout(timerId);
  284. timerId = Meteor.setTimeout(callback, remaining);
  285. timeWhenPaused += new Date() - timePaused;
  286. };
  287. this.timeWhenPaused = function () {
  288. return timeWhenPaused;
  289. };
  290. this.resume();
  291. }
  292. Meteor.users.deny({
  293. update: function () {
  294. return true;
  295. }
  296. });
  297. Meteor.users.deny({
  298. insert: function () {
  299. return true;
  300. }
  301. });
  302. Meteor.users.deny({
  303. remove: function () {
  304. return true;
  305. }
  306. });
  307. function getSongDuration(query, artistName) {
  308. var duration;
  309. var search = query;
  310. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  311. for (var i in res.data) {
  312. for (var j in res.data[i].items) {
  313. if (search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1) {
  314. duration = res.data[i].items[j].duration_ms / 1000;
  315. return duration;
  316. }
  317. }
  318. }
  319. return 0;
  320. }
  321. function getSongAlbumArt(query, artistName) {
  322. var albumart;
  323. var search = query;
  324. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  325. for (var i in res.data) {
  326. for (var j in res.data[i].items) {
  327. if (search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1) {
  328. albumart = res.data[i].items[j].album.images[1].url
  329. return albumart;
  330. }
  331. }
  332. }
  333. }
  334. //var room_types = ["edm", "nightcore"];
  335. var songsArr = [];
  336. Rooms.find({}).fetch().forEach(function (room) {
  337. var type = room.type;
  338. if (Playlists.find({type: type}).count() === 0) {
  339. Playlists.insert({type: type, songs: []});
  340. }
  341. if (Playlists.findOne({type: type}).songs.length === 0) {
  342. // Add a global video to Playlist so it can proceed
  343. } else {
  344. stations.push(new Station(type));
  345. }
  346. });
  347. Accounts.validateNewUser(function (user) {
  348. var username;
  349. if (user.services) {
  350. if (user.services.github) {
  351. username = user.services.github.username;
  352. } else if (user.services.facebook) {
  353. username = user.services.facebook.first_name;
  354. } else if (user.services.password) {
  355. username = user.username;
  356. }
  357. }
  358. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() !== 0) {
  359. throw new Meteor.Error(403, "An account with that username already exists.");
  360. } else {
  361. return true;
  362. }
  363. });
  364. Accounts.onCreateUser(function (options, user) {
  365. var username;
  366. if (user.services) {
  367. if (user.services.github) {
  368. username = user.services.github.username;
  369. } else if (user.services.facebook) {
  370. username = user.services.facebook.first_name;
  371. } else if (user.services.password) {
  372. username = user.username;
  373. }
  374. }
  375. user.profile = {
  376. username: username,
  377. usernameL: username.toLowerCase(),
  378. rank: "default",
  379. liked: [],
  380. disliked: [],
  381. settings: {showRating: false},
  382. realname: ""
  383. };
  384. return user;
  385. });
  386. Meteor.publish("alerts", function () {
  387. return Alerts.find({active: true})
  388. });
  389. Meteor.publish("userData", function (userId) {
  390. if (userId !== undefined) {
  391. return Meteor.users.find(userId, {fields: {"services.github.username": 1, "punishments": 1}})
  392. } else {
  393. return undefined;
  394. }
  395. });
  396. Meteor.publish("allAlerts", function () {
  397. return Alerts.find({active: false})
  398. });
  399. Meteor.publish("playlists", function () {
  400. return Playlists.find({})
  401. });
  402. Meteor.publish("rooms", function () {
  403. return Rooms.find({});
  404. });
  405. Meteor.publish("songs", function () {
  406. return Songs.find({});
  407. });
  408. Meteor.publish("queues", function () {
  409. return Queues.find({});
  410. });
  411. Meteor.publish("reports", function () {
  412. return Reports.find({});
  413. });
  414. Meteor.publish("chat", function () {
  415. return Chat.find({});
  416. });
  417. Meteor.publish("userProfiles", function (username) {
  418. var settings = Meteor.users.findOne({"profile.usernameL": username}, {fields: {"profile.settings": 1}});
  419. if (settings !== undefined && settings.profile.settings) {
  420. settings = settings.profile.settings;
  421. if (settings.showRating === true) {
  422. return Meteor.users.find({"profile.usernameL": username}, {
  423. fields: {
  424. "profile.username": 1,
  425. "profile.usernameL": 1,
  426. "profile.rank": 1,
  427. createdAt: 1,
  428. "profile.liked": 1,
  429. "profile.disliked": 1,
  430. "profile.settings": 1,
  431. "profile.realname": 1
  432. }
  433. });
  434. }
  435. }
  436. return Meteor.users.find({"profile.usernameL": username}, {
  437. fields: {
  438. "profile.username": 1,
  439. "profile.usernameL": 1,
  440. "profile.rank": 1,
  441. createdAt: 1,
  442. "profile.settings": 1,
  443. "profile.realname": 1
  444. }
  445. });
  446. });
  447. Meteor.publish("isAdmin", function () {
  448. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  449. });
  450. Meteor.publish("isModerator", function () {
  451. return Meteor.users.find({_id: this.userId, "profile.rank": "moderator"});
  452. });
  453. Meteor.publish("feedback", function(){
  454. return Feedback.find();
  455. })
  456. function isAdmin() {
  457. var userData = Meteor.users.find(Meteor.userId());
  458. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  459. return true;
  460. } else {
  461. return false;
  462. }
  463. }
  464. function isModerator() {
  465. var userData = Meteor.users.find(Meteor.userId());
  466. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  467. return true;
  468. } else {
  469. return isAdmin();
  470. }
  471. }
  472. function isBanned() {
  473. var userData = Meteor.users.findOne(Meteor.userId());
  474. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  475. var ban = userData.punishments.ban;
  476. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  477. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  478. return false;
  479. } else {
  480. return true;
  481. }
  482. } else {
  483. return false;
  484. }
  485. }
  486. function isMuted() {
  487. var userData = Meteor.users.findOne(Meteor.userId());
  488. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.mute !== undefined) {
  489. var mute = userData.punishments.mute;
  490. if (new Date(mute.bannedUntil).getTime() <= new Date().getTime()) {
  491. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.mute": ""}});
  492. return false;
  493. } else {
  494. return true;
  495. }
  496. } else {
  497. return false;
  498. }
  499. }
  500. Meteor.methods({
  501. getSongAudio: function(url) {
  502. var ytdl = Meteor.npmRequire("ytdl-core");
  503. var stream = ytdl(url);
  504. console.log(url);
  505. var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  506. var analyser = audioCtx.createAnalyser();
  507. var source = audioCtx.createMediaStreamSource(stream);
  508. source.connect(analyser);
  509. analyser.connect(distortion);
  510. },
  511. lockRoom: function (type) {
  512. if (isAdmin() && !isBanned()) {
  513. getStation(type, function (station) {
  514. station.lock();
  515. });
  516. } else {
  517. throw new Meteor.Error(403, "Invalid permissions.");
  518. }
  519. },
  520. unlockRoom: function (type) {
  521. if (isAdmin() && !isBanned()) {
  522. getStation(type, function (station) {
  523. station.unlock();
  524. });
  525. } else {
  526. throw new Meteor.Error(403, "Invalid permissions.");
  527. }
  528. },
  529. banUser: function (username, period, reason) {
  530. if (isAdmin() && !isBanned()) {
  531. var user = Meteor.user();
  532. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  533. var bannedUntil = (new Date).getTime() + (period * 1000);
  534. if (bannedUntil > 8640000000000000) {
  535. bannedUntil = 8640000000000000;
  536. }
  537. bannedUntil = new Date(bannedUntil);
  538. var banObject = {
  539. bannedBy: user.profile.usernameL,
  540. bannedAt: new Date(Date.now()),
  541. bannedReason: reason,
  542. bannedUntil: bannedUntil
  543. };
  544. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  545. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  546. } else {
  547. throw new Meteor.Error(403, "Invalid permissions.");
  548. }
  549. },
  550. muteUser: function (username, period) {
  551. if (isAdmin() && !isBanned()) {
  552. var user = Meteor.user();
  553. var mutedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  554. if (period === undefined || Number(period) === 0) {
  555. mutedUntil = 8640000000000000;
  556. } else {
  557. var mutedUntil = (new Date).getTime() + (period * 1000);
  558. if (mutedUntil > 8640000000000000) {
  559. mutedUntil = 8640000000000000;
  560. }
  561. }
  562. mutedUntil = new Date(mutedUntil);
  563. var muteObject = {mutedBy: user.profile.usernameL, mutedAt: new Date(Date.now()), mutedUntil: mutedUntil};
  564. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$set: {"punishments.mute": muteObject}});
  565. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$push: {"punishments.mutes": muteObject}});
  566. } else {
  567. throw new Meteor.Error(403, "Invalid permissions.");
  568. }
  569. },
  570. unbanUser: function (username) {
  571. if (isAdmin() && !isBanned()) {
  572. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.ban"});
  573. } else {
  574. throw new Meteor.Error(403, "Invalid permissions.");
  575. }
  576. },
  577. unsilenceUser: function (username) {
  578. if (isAdmin() && !isBanned()) {
  579. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.mute"});
  580. } else {
  581. throw new Meteor.Error(403, "Invalid permissions.");
  582. }
  583. },
  584. isBanned: function () {
  585. return isBanned();
  586. },
  587. isMuted: function () {
  588. return isMuted();
  589. },
  590. updateSettings: function (showRating) {
  591. if (Meteor.userId() && !isBanned()) {
  592. var user = Meteor.user();
  593. if (showRating !== true && showRating !== false) {
  594. showRating = false;
  595. }
  596. if (user.profile.settings) {
  597. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  598. } else {
  599. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  600. }
  601. } else {
  602. throw new Meteor.Error(403, "Invalid permissions.");
  603. }
  604. },
  605. resetRating: function () {
  606. if (isAdmin() && !isBanned()) {
  607. stations.forEach(function (station) {
  608. var type = station.type;
  609. var temp_songs = Playlists.findOne({type: type}).songs;
  610. Playlists.update({type: type}, {$set: {"songs": []}});
  611. temp_songs.forEach(function (song) {
  612. song.likes = 0;
  613. song.dislikes = 0;
  614. Playlists.update({type: type}, {$push: {"songs": song}});
  615. });
  616. });
  617. Meteor.users.update({}, {$set: {"profile.liked": [], "profile.disliked": []}}, {multi: true});
  618. } else {
  619. throw Meteor.Error(403, "Invalid permissions.");
  620. }
  621. },
  622. removeAlerts: function () {
  623. if (isAdmin() && !isBanned()) {
  624. Alerts.update({active: true}, {$set: {active: false}}, {multi: true});
  625. } else {
  626. throw Meteor.Error(403, "Invalid permissions.");
  627. }
  628. },
  629. addAlert: function (description, priority) {
  630. if (isAdmin()) {
  631. if (description.length > 0 && description.length < 400) {
  632. var username = Meteor.user().profile.username;
  633. if (["danger", "warning", "success", "primary"].indexOf(priority) === -1) {
  634. priority = "warning";
  635. }
  636. Alerts.insert({description: description, priority: priority, active: true, createdBy: username});
  637. return true;
  638. } else {
  639. throw Meteor.Error(403, "Invalid description length.");
  640. }
  641. } else {
  642. throw Meteor.Error(403, "Invalid permissions.");
  643. }
  644. },
  645. sendMessage: function (type, message) {
  646. if (Meteor.userId() && !isBanned() && !isMuted()) {
  647. var user = Meteor.user();
  648. var time = new Date();
  649. var rawrank = user.profile.rank;
  650. var username = user.profile.username;
  651. var profanity = false;
  652. var mentionUsername;
  653. var isCurUserMentioned;
  654. if (message.indexOf("@") !== -1) {
  655. var messageArr = message.split(" ");
  656. for (var i in messageArr) {
  657. if (messageArr[i].indexOf("@") !== -1) {
  658. var mention = messageArr[i];
  659. }
  660. }
  661. Meteor.users.find().forEach(function (user) {
  662. if (mention.indexOf(user.profile.username) !== -1) {
  663. mentionUsername = true;
  664. isCurUserMentioned = Meteor.user().profile.username === user.profile.username;
  665. }
  666. ;
  667. })
  668. }
  669. if (!message.replace(/\s/g, "").length > 0) {
  670. throw new Meteor.Error(406, "Message length cannot be 0.");
  671. }
  672. if (message.length > 300) {
  673. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  674. }
  675. else if (user.profile.rank === "admin") {
  676. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  677. if (res.content.indexOf("true") > -1) {
  678. return true;
  679. } else {
  680. Chat.insert({
  681. type: type,
  682. rawrank: rawrank,
  683. rank: "[A]",
  684. message: message,
  685. curUserMention: isCurUserMentioned,
  686. isMentioned: mentionUsername,
  687. time: time,
  688. username: username
  689. });
  690. }
  691. });
  692. return true;
  693. }
  694. else if (user.profile.rank === "moderator") {
  695. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  696. if (res.content.indexOf("true") > -1) {
  697. return true;
  698. } else {
  699. Chat.insert({
  700. type: type,
  701. rawrank: rawrank,
  702. rank: "[M]",
  703. message: message,
  704. time: time,
  705. username: username
  706. });
  707. }
  708. });
  709. return true;
  710. }
  711. else {
  712. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  713. if (res.content.indexOf("true") > -1) {
  714. return true;
  715. } else {
  716. Chat.insert({
  717. type: type,
  718. rawrank: rawrank,
  719. rank: "",
  720. message: message,
  721. time: time,
  722. username: username
  723. });
  724. }
  725. });
  726. return true;
  727. }
  728. } else {
  729. throw new Meteor.Error(403, "Invalid permissions.");
  730. }
  731. },
  732. likeSong: function (mid) {
  733. if (Meteor.userId() && !isBanned()) {
  734. var user = Meteor.user();
  735. if (user.profile.liked.indexOf(mid) === -1) {
  736. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  737. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": 1}})
  738. } else {
  739. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  740. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}})
  741. }
  742. if (user.profile.disliked.indexOf(mid) !== -1) {
  743. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  744. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}})
  745. }
  746. return true;
  747. } else {
  748. throw new Meteor.Error(403, "Invalid permissions.");
  749. }
  750. },
  751. dislikeSong: function (mid) {
  752. if (Meteor.userId() && !isBanned()) {
  753. var user = Meteor.user();
  754. if (user.profile.disliked.indexOf(mid) === -1) {
  755. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  756. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": 1}});
  757. } else {
  758. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  759. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}});
  760. }
  761. if (user.profile.liked.indexOf(mid) !== -1) {
  762. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  763. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}});
  764. }
  765. return true;
  766. } else {
  767. throw new Meteor.Error(403, "Invalid permissions.");
  768. }
  769. },
  770. voteSkip: function (type) {
  771. if (Meteor.userId() && !isBanned()) {
  772. var user = Meteor.user();
  773. getStation(type, function (station) {
  774. if (station.voted.indexOf(user.profile.username) === -1) {
  775. station.voted.push(user.profile.username);
  776. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  777. if (station.voted.length === 3) {
  778. station.skipSong();
  779. }
  780. } else {
  781. throw new Meteor.Error(401, "Already voted.");
  782. }
  783. })
  784. }
  785. },
  786. submitReport: function (room, reportData) {
  787. if (Meteor.userId() && !isBanned()) {
  788. room = room.toLowerCase();
  789. if (Rooms.find({type: room}).count() === 1) {
  790. if (Reports.find({room: room}).count() === 0) {
  791. Reports.insert({room: room, report: []});
  792. }
  793. if (reportData !== undefined) {
  794. Reports.update({room: room}, {
  795. $push: {
  796. report: {
  797. song: reportData.song,
  798. type: reportData.type,
  799. reason: reportData.reason,
  800. other: reportData.other
  801. }
  802. }
  803. });
  804. return true;
  805. } else {
  806. throw new Meteor.Error(403, "Invalid data.");
  807. }
  808. } else {
  809. throw new Meteor.Error(403, "Invalid genre.");
  810. }
  811. } else {
  812. throw new Meteor.Error(403, "Invalid permissions.");
  813. }
  814. },
  815. shufflePlaylist: function (type) {
  816. if (isAdmin() && !isBanned()) {
  817. getStation(type, function (station) {
  818. if (station === undefined) {
  819. throw new Meteor.Error(404, "Station not found.");
  820. } else {
  821. station.cancelTimer();
  822. station.shufflePlaylist();
  823. }
  824. });
  825. }
  826. },
  827. skipSong: function (type) {
  828. if (isAdmin() && !isBanned()) {
  829. getStation(type, function (station) {
  830. if (station === undefined) {
  831. throw new Meteor.Error(404, "Station not found.");
  832. } else {
  833. station.skipSong();
  834. }
  835. });
  836. }
  837. },
  838. pauseRoom: function (type) {
  839. if (isAdmin() && !isBanned()) {
  840. getStation(type, function (station) {
  841. if (station === undefined) {
  842. throw new Meteor.Error(403, "Room doesn't exist.");
  843. } else {
  844. station.pauseRoom();
  845. }
  846. });
  847. } else {
  848. throw new Meteor.Error(403, "Invalid permissions.");
  849. }
  850. },
  851. resumeRoom: function (type) {
  852. if (isAdmin() && !isBanned()) {
  853. getStation(type, function (station) {
  854. if (station === undefined) {
  855. throw new Meteor.Error(403, "Room doesn't exist.");
  856. } else {
  857. station.resumeRoom();
  858. }
  859. });
  860. } else {
  861. throw new Meteor.Error(403, "Invalid permissions.");
  862. }
  863. },
  864. createUserMethod: function (formData, captchaData) {
  865. if (!isBanned()) {
  866. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  867. if (!verifyCaptchaResponse.success) {
  868. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  869. } else {
  870. Accounts.createUser({
  871. username: formData.username,
  872. email: formData.email,
  873. password: formData.password
  874. });
  875. }
  876. return true;
  877. }
  878. },
  879. addSongToQueue: function (songData) {
  880. if (Meteor.userId() && !isBanned()) {
  881. var userId = Meteor.userId();
  882. var requiredProperties = ["title", "artist", "img", "id", "genres"];
  883. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  884. for (var property in requiredProperties) {
  885. if (songData[requiredProperties[property]] === undefined) {
  886. throw new Meteor.Error(403, "Invalid data.");
  887. }
  888. }
  889. songData.duration = Number(getSongDuration(songData.title, songData.artist));
  890. songData.img = getSongAlbumArt(songData.title, songData.artist) || "";
  891. songData.skipDuration = 0;
  892. songData.likes = 0;
  893. songData.dislikes = 0;
  894. songData.requestedBy = userId;
  895. var mid = createUniqueSongId();
  896. if (mid !== undefined) {
  897. songData.mid = mid;
  898. Queues.insert(songData, function(err, res) {
  899. if (err) {
  900. console.log(err);
  901. throw err.sanitizedError;
  902. } else {
  903. var songsRequested = (Meteor.user().profile !== undefined && Meteor.user().profile.statistics !== undefined && Meteor.user().profile.statistics.songsRequested !== undefined) ? Meteor.user().profile.statistics.songsRequested : 0;
  904. songsRequested++;
  905. Meteor.users.update(Meteor.userId(), {$set: {"profile.statistics.songsRequested": songsRequested}}); // TODO Make mongo query use $inc correctly.
  906. return true;
  907. }
  908. });
  909. } else {
  910. throw new Meteor.Error(500, "Am error occured.");
  911. }
  912. } else {
  913. throw new Meteor.Error(403, "Invalid data.");
  914. }
  915. } else {
  916. throw new Meteor.Error(403, "Invalid permissions.");
  917. }
  918. },
  919. updateQueueSong: function (mid, newSong) {
  920. if (isModerator() && !isBanned()) {
  921. newSong.mid = mid;
  922. Queues.update({mid: mid}, newSong, function(err) {
  923. console.log(err);
  924. if (err) {
  925. throw err.sanitizedError;
  926. } else {
  927. return true;
  928. }
  929. });
  930. } else {
  931. throw new Meteor.Error(403, "Invalid permissions.");
  932. }
  933. },
  934. updatePlaylistSong: function (mid, newSong) {
  935. if (isModerator() && !isBanned()) {
  936. newSong.mid = mid;
  937. newSong.approvedBy = Meteor.userId();
  938. Playlists.update({mid: mid}, newSong, function(err) {
  939. console.log(err);
  940. if (err) {
  941. throw err.sanitizedError;
  942. } else {
  943. return true;
  944. }
  945. });
  946. return true;
  947. } else {
  948. throw new Meteor.Error(403, "Invalid permissions.");
  949. }
  950. },
  951. removeSongFromQueue: function (mid) {
  952. if (isModerator() && !isBanned()) {
  953. Queues.remove({mid: mid});
  954. } else {
  955. throw new Meteor.Error(403, "Invalid permissions.");
  956. }
  957. },
  958. removeSongFromPlaylist: function (mid) {
  959. if (isModerator() && !isBanned()) {
  960. Playlists.remove({}, {$pull: {songs: mid}});
  961. var song = Songs.findOne({mid: mid});
  962. Songs.remove({mid: mid});
  963. if (song !== undefined) {
  964. song.deletedBy = Meteor.userId();
  965. song.deletedAt = new Date(Date.now());
  966. song.deletedType = "song";
  967. Deleted.insert(song);
  968. }
  969. } else {
  970. throw new Meteor.Error(403, "Invalid permissions.");
  971. }
  972. },
  973. addSongToPlaylist: function (songData) {
  974. if (isModerator() && !isBanned()) {
  975. var requiredProperties = ["_id", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes", "requestedBy", "genres"];
  976. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  977. for (var property in requiredProperties) {
  978. if (songData[requiredProperties[property]] === undefined) {
  979. throw new Meteor.Error(403, "Invalid data.");
  980. }
  981. }
  982. delete songData._id;
  983. songData.approvedBy = Meteor.userId();
  984. Songs.insert(songData);
  985. Queues.remove({mid: songData.mid});
  986. songData.genres.forEach(function(genre) {
  987. genre = genre.toLowerCase();
  988. if (Playlists.findOne({type: genre}) === undefined) {
  989. Playlists.insert({type: genre, songs: [songData.mid]});
  990. } else {
  991. Playlists.update({type: genre}, {$push: {songs: songData.mid}});
  992. }
  993. });
  994. return true;
  995. } else {
  996. throw new Meteor.Error(403, "Invalid data.");
  997. }
  998. } else {
  999. throw new Meteor.Error(403, "Invalid permissions.");
  1000. }
  1001. },
  1002. createRoom: function (display, tag, private) {
  1003. if (isAdmin() && !isBanned()) {
  1004. createRoom(display, tag, private);
  1005. } else {
  1006. throw new Meteor.Error(403, "Invalid permissions.");
  1007. }
  1008. },
  1009. deleteRoom: function (type) {
  1010. if (isAdmin() && !isBanned()) {
  1011. Rooms.remove({type: type});
  1012. return true;
  1013. } else {
  1014. throw new Meteor.Error(403, "Invalid permissions.");
  1015. }
  1016. },
  1017. getUserNum: function () {
  1018. if (!isBanned()) {
  1019. return Object.keys(Meteor.default_server.sessions).length;
  1020. }
  1021. },
  1022. getTotalUsers: function () {
  1023. return Meteor.users.find().count();
  1024. },
  1025. updateRealName: function (realname) {
  1026. if (Meteor.userId()) {
  1027. var oldName = Meteor.users.findOne(Meteor.userId()).profile.realname;
  1028. Meteor.users.update(Meteor.userId(), {
  1029. $set: {"profile.realname": realname},
  1030. $push: {"profile.realnames": oldName}
  1031. });
  1032. } else {
  1033. throw new Meteor.Error(403, "Invalid permissions.");
  1034. }
  1035. },
  1036. updateUserName: function (newUserName) {
  1037. if (Meteor.userId()) {
  1038. var oldUsername = Meteor.users.findOne(Meteor.userId()).profile.username;
  1039. Meteor.users.update(Meteor.userId(), {
  1040. $set: {
  1041. "username": newUserName,
  1042. "profile.username": newUserName,
  1043. "profile.usernameL": newUserName.toLowerCase()
  1044. }, $push: {"profile.usernames": oldUsername}
  1045. });
  1046. } else {
  1047. throw new Meteor.Error(403, "Invalid permissions.");
  1048. }
  1049. },
  1050. /*updateUserRank: function(newRank){
  1051. if (Meteor.userId()) {
  1052. Meteor.users.update(Meteor.userId(), {$set: {"profile.rank": newRank}});
  1053. } else {
  1054. throw new Meteor.Error(403, "Invalid permissions.");
  1055. }
  1056. },*/
  1057. deleteAccount: function () {
  1058. if (Meteor.userId()) {
  1059. var user = Meteor.users.findOne(Meteor.userId());
  1060. Meteor.users.remove({_id: Meteor.userId()});
  1061. } else {
  1062. throw new Meteor.Error(403, "Invalid permissions.");
  1063. }
  1064. },
  1065. sendFeedback: function(message){
  1066. if(Meteor.userId() && !isBanned()) {
  1067. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1068. if (res.content.indexOf("true") > -1) {
  1069. return true;
  1070. } else {
  1071. Feedback.insert({
  1072. "username": Meteor.user().profile.username,
  1073. "message": message,
  1074. upvotes: 0,
  1075. upvotedBy: []
  1076. })
  1077. }
  1078. });
  1079. }
  1080. },
  1081. upvoteFeedback: function(message){
  1082. if(Meteor.userId() && !isBanned()){
  1083. console.log(Feedback.findOne({"message": message}));
  1084. if(Feedback.findOne({"message": message}).upvotedBy.indexOf(Meteor.user().profile.username) === -1){
  1085. Feedback.update({"message": message}, {$inc: {"upvotes": 1}});
  1086. Feedback.update({"message": message}, {$push: {"upvotedBy": Meteor.user().profile.username}});
  1087. } else{
  1088. Feedback.update({"message": message}, {$inc: {"upvotes": -1}});
  1089. Feedback.update({"message": message}, {$pull: {"upvotedBy": Meteor.user().profile.username}});
  1090. }
  1091. }
  1092. },
  1093. deleteFeedback: function(message){
  1094. if(isAdmin() && !isBanned()){
  1095. Feedback.remove({"message": message});
  1096. } else {
  1097. throw new Meteor.Error(403, "Invalid permissions.");
  1098. }
  1099. },
  1100. updateFeedback: function(oldMessage, newMessage){
  1101. if(isAdmin() && !isBanned()){
  1102. Feedback.update({"message": oldMessage}, {$set: {"message": newMessage}});
  1103. } else {
  1104. throw new Meteor.Error(403, "Invalid permissions.");
  1105. }
  1106. },
  1107. editRoomDesc: function(type, description){
  1108. if(isAdmin() && !isBanned()){
  1109. Rooms.update({type: type}, {$set: {"roomDesc": description}});
  1110. } else {
  1111. throw new Meteor.Error(403, "Invalid permissions.");
  1112. }
  1113. }
  1114. });
  1115. Meteor.setInterval(function () {
  1116. checkUsersPR();
  1117. }, 10000);
  1118. Meteor.users.after.insert(function (err, user) {
  1119. Accounts.sendVerificationEmail(user._id);
  1120. });