server.js 44 KB

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