server.js 43 KB

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