server.js 44 KB

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