server.js 44 KB

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