server.js 43 KB

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