2
0

server.js 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. Meteor.startup(function () {
  2. reCAPTCHA.config({
  3. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  4. });
  5. Avatar.setOptions({
  6. fallbackType: "initials",
  7. defaultImageUrl: "http://static.boredpanda.com/blog/wp-content/uploads/2014/04/amazing-fox-photos-182.jpg",
  8. generateCSS: true,
  9. imageSizes: {
  10. 'header': 40
  11. }
  12. });
  13. var stations = [{tag: "edm", display: "EDM"}, {tag: "pop", display: "Pop"}]; //Rooms to be set on server startup
  14. for (var i in stations) {
  15. if (Rooms.find({type: stations[i]}).count() === 0) {
  16. createRoom(stations[i].display, stations[i].tag, false, "Room description goes here.");
  17. }
  18. }
  19. emojione.ascii = true;
  20. Accounts.config({
  21. sendVerificationEmail: true
  22. });
  23. if (Songs.find().count() === 0 || Songs.find({mid: default_song.mid}).count() === 0) {
  24. Songs.insert(default_song);
  25. }
  26. });
  27. var default_song = {
  28. id: "xKVcVSYmesU",
  29. mid: "ABCDEF",
  30. likes: 0,
  31. dislikes: 0,
  32. title: "Immortals",
  33. artist: "Fall Out Boy",
  34. img: "http://c.directlyrics.com/img/upload/fall-out-boy-sixth-album-cover.jpg",
  35. type: "YouTube",
  36. duration: 181,
  37. skipDuration: 0,
  38. requestedBy: "NONE",
  39. approvedBy: "GOD",
  40. genres: []
  41. };
  42. Alerts.update({active: true}, {$set: {active: false}}, {multi: true});
  43. var stations = [];
  44. var voteNum = 0;
  45. var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
  46. function createUniqueSongId() {
  47. var code = "";
  48. for (var i = 0; i < 6; i++) {
  49. code += chars[Math.floor(Math.random() * chars.length)];
  50. }
  51. if (Playlists.find({"songs.mid": code}).count() > 0) {
  52. return createUniqueSongId();
  53. } else {
  54. return code;
  55. }
  56. }
  57. function checkUsersPR() {
  58. var output = {};
  59. var connections = Meteor.server.stream_server.open_sockets;
  60. _.each(connections, function (connection) {
  61. // named subscriptions
  62. if (connection._meteorSession !== undefined && connection._meteorSession !== null) {
  63. var subs = connection._meteorSession._namedSubs;
  64. //var ip = connection.remoteAddress;
  65. var used_subs = [];
  66. for (var sub in subs) {
  67. var mySubName = subs[sub]._name;
  68. if (subs[sub]._params.length > 0) {
  69. mySubName += subs[sub]._params[0]; // assume one id parameter for now
  70. }
  71. if (used_subs.indexOf(mySubName) === -1) {
  72. used_subs.push(mySubName);
  73. if (!output[mySubName]) {
  74. output[mySubName] = 1;
  75. } else {
  76. output[mySubName] += 1;
  77. }
  78. }
  79. }
  80. }
  81. // there are also these 'universal subscriptions'
  82. //not sure what these are, i count none in my tests
  83. //var usubs = connection._meteorSession._universalSubs;
  84. });
  85. var emptyStations = [];
  86. stations.forEach(function (station) {
  87. emptyStations.push(station);
  88. });
  89. for (var key in output) {
  90. getStation(key, function (station) {
  91. emptyStations.splice(emptyStations.indexOf(station), 1);
  92. Rooms.update({type: key}, {$set: {users: output[key]}});
  93. });
  94. }
  95. emptyStations.forEach(function (emptyStation) {
  96. Rooms.update({type: emptyStation.type}, {$set: {users: 0}});
  97. });
  98. return output;
  99. }
  100. function getStation(type, cb) {
  101. stations.forEach(function (station) {
  102. if (station.type === type) {
  103. cb(station);
  104. return;
  105. }
  106. });
  107. }
  108. function createRoom(display, tag, private, desc) {
  109. var type = tag;
  110. if (Rooms.find({type: type}).count() === 0) {
  111. Rooms.insert({
  112. display: display,
  113. type: type,
  114. users: 0,
  115. private: private,
  116. currentSong: {song: default_song, started: 0},
  117. roomDesc: desc
  118. }, function (err) {
  119. if (err) {
  120. throw err;
  121. } else {
  122. stations.push(new Station(type));
  123. }
  124. });
  125. } else {
  126. return "Room already exists";
  127. }
  128. }
  129. function Station(type) {
  130. console.log(type);
  131. if (Playlists.find({type: type}).count() === 0) {
  132. Playlists.insert({type: type, songs: [default_song.mid], lastSong: 0});
  133. }
  134. if (Songs.find({genres: type}).count() > 0) {
  135. var list = Songs.find({genres: type}).fetch();
  136. list.forEach(function(song){
  137. if (Playlists.findOne({type: type, songs: song.mid}) === undefined) {
  138. Playlists.update({type: type}, {$push: {songs: song.mid}});
  139. }
  140. });
  141. }
  142. if (Playlists.findOne({type: type}).songs.length === 0) {
  143. Playlists.update({type: type}, {$push: {songs: default_song.mid}});
  144. }
  145. Meteor.publish(type, function () {
  146. return undefined;
  147. });
  148. var self = this;
  149. var startedAt = Date.now();
  150. var playlist = Playlists.findOne({type: type});
  151. var songs = playlist.songs;
  152. var currentSong = playlist.lastSong;
  153. if (currentSong < (songs.length - 1)) {
  154. currentSong++;
  155. } else currentSong = 0;
  156. var currentMid = songs[currentSong];
  157. var song = Songs.findOne({mid: currentMid});
  158. if (song === undefined) {
  159. Playlists.remove({}, {$pull: {songs: currentMid}});
  160. song = default_song;
  161. }
  162. console.log(startedAt);
  163. console.log(song);
  164. var res = Rooms.update({type: type}, {
  165. $set: {
  166. currentSong: {song: song, started: startedAt},
  167. users: 0
  168. }
  169. });
  170. console.log(res);
  171. this.skipSong = function () {
  172. self.voted = [];
  173. voteNum = 0;
  174. Rooms.update({type: type}, {$set: {votes: 0}});
  175. songs = Playlists.findOne({type: type}).songs;
  176. songs.forEach(function (mid, index) {
  177. if (mid === currentMid) {
  178. currentSong = index;
  179. }
  180. });
  181. if (currentSong < (songs.length - 1)) {
  182. currentSong++;
  183. } else currentSong = 0;
  184. if (songs);
  185. if (currentSong === 0) {
  186. this.shufflePlaylist();
  187. } else {
  188. currentMid = songs[currentSong];
  189. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  190. Rooms.update({type: type}, {$set: {timePaused: 0}});
  191. this.songTimer();
  192. Rooms.update({type: type}, {$set: {currentSong: {song: Songs.findOne({mid: songs[currentSong]}), started: startedAt}}});
  193. }
  194. };
  195. this.shufflePlaylist = function () {
  196. voteNum = 0;
  197. Rooms.update({type: type}, {$set: {votes: 0}});
  198. self.voted = [];
  199. songs = Playlists.findOne({type: type}).songs;
  200. currentSong = 0;
  201. Playlists.update({type: type}, {$set: {"songs": []}});
  202. songs = shuffle(songs);
  203. songs.forEach(function (song) {
  204. Playlists.update({type: type}, {$push: {"songs": song}});
  205. });
  206. currentMid = songs[currentSong];
  207. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  208. Rooms.update({type: type}, {$set: {timePaused: 0}});
  209. this.songTimer();
  210. Rooms.update({type: type}, {$set: {currentSong: {song: Songs.findOne({mid: songs[currentSong]}), started: startedAt}}});
  211. };
  212. Rooms.update({type: type}, {$set: {timePaused: 0}});
  213. var timer;
  214. this.songTimer = function () {
  215. startedAt = Date.now();
  216. if (timer !== undefined) {
  217. timer.pause();
  218. }
  219. timer = new Timer(function () {
  220. self.skipSong();
  221. }, Songs.findOne({mid: songs[currentSong]}).duration * 1000);
  222. };
  223. var state = Rooms.findOne({type: type}).state;
  224. this.pauseRoom = function () {
  225. if (state !== "paused") {
  226. timer.pause();
  227. Rooms.update({type: type}, {$set: {state: "paused"}});
  228. state = "paused";
  229. }
  230. };
  231. this.resumeRoom = function () {
  232. if (state !== "playing") {
  233. timer.resume();
  234. Rooms.update({type: type}, {$set: {state: "playing", timePaused: timer.timeWhenPaused()}});
  235. state = "playing";
  236. }
  237. };
  238. this.cancelTimer = function () {
  239. timer.pause();
  240. };
  241. this.getState = function () {
  242. return state;
  243. };
  244. this.type = type;
  245. var private = Rooms.findOne({type: type}).private;
  246. if (typeof private !== "boolean") {
  247. Rooms.update({type: type}, {$set: {"private": false}});
  248. private = false;
  249. }
  250. this.private = private;
  251. this.unlock = function () {
  252. if (self.private) {
  253. self.private = false;
  254. Rooms.update({type: type}, {$set: {"private": false}});
  255. }
  256. };
  257. this.lock = function () {
  258. if (!self.private) {
  259. self.private = true;
  260. Rooms.update({type: type}, {$set: {"private": true}});
  261. }
  262. };
  263. /* This function fetches all songs with the genre of this room that isn't in the playlist yet, and then puts it in the playlist */
  264. this.fetchSongs = function() {
  265. var genreSongs = Songs.find({genres: type}).fetch();
  266. genreSongs.forEach(function(song) {
  267. if (songs.indexOf(song.mid) === -1) {
  268. Playlists.update({type: type}, {$push: {songs: song.mid}});
  269. }
  270. });
  271. };
  272. /* This function removes all songs that are in the playlist but do not have the type of the playlist in their genre */
  273. this.removeSongs = function() {
  274. songs.forEach(function(mid) {
  275. var song = Songs.findOne({mid: mid});
  276. if (song === undefined || song.genres.indexOf(type) === -1) {
  277. Playlists.update({type: type}, {$pull: {songs: mid}});
  278. }
  279. });
  280. };
  281. this.removeSongs();
  282. this.fetchSongs();
  283. this.skipSong();
  284. this.voted = [];
  285. }
  286. function shuffle(array) {
  287. var currentIndex = array.length, temporaryValue, randomIndex;
  288. // While there remain elements to shuffle...
  289. while (0 !== currentIndex) {
  290. // Pick a remaining element...
  291. randomIndex = Math.floor(Math.random() * currentIndex);
  292. currentIndex -= 1;
  293. // And swap it with the current element.
  294. temporaryValue = array[currentIndex];
  295. array[currentIndex] = array[randomIndex];
  296. array[randomIndex] = temporaryValue;
  297. }
  298. return array;
  299. }
  300. function Timer(callback, delay) {
  301. var timerId, start, remaining = delay;
  302. var timeWhenPaused = 0;
  303. var timePaused = new Date();
  304. this.pause = function () {
  305. Meteor.clearTimeout(timerId);
  306. remaining -= new Date() - start;
  307. timePaused = new Date();
  308. };
  309. this.resume = function () {
  310. start = new Date();
  311. Meteor.clearTimeout(timerId);
  312. timerId = Meteor.setTimeout(callback, remaining);
  313. timeWhenPaused += new Date() - timePaused;
  314. };
  315. this.timeWhenPaused = function () {
  316. return timeWhenPaused;
  317. };
  318. this.resume();
  319. }
  320. Meteor.users.deny({
  321. update: function () {
  322. return true;
  323. }
  324. });
  325. Meteor.users.deny({
  326. insert: function () {
  327. return true;
  328. }
  329. });
  330. Meteor.users.deny({
  331. remove: function () {
  332. return true;
  333. }
  334. });
  335. function getSongDuration(query, artistName) {
  336. var duration;
  337. var search = query;
  338. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  339. for (var i in res.data) {
  340. for (var j in res.data[i].items) {
  341. if (search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1) {
  342. duration = res.data[i].items[j].duration_ms / 1000;
  343. return duration;
  344. }
  345. }
  346. }
  347. return 0;
  348. }
  349. function getSongAlbumArt(query, artistName) {
  350. var albumart;
  351. var search = query;
  352. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  353. for (var i in res.data) {
  354. for (var j in res.data[i].items) {
  355. if (search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1) {
  356. albumart = res.data[i].items[j].album.images[1].url
  357. return albumart;
  358. }
  359. }
  360. }
  361. }
  362. //var room_types = ["edm", "nightcore"];
  363. var songsArr = [];
  364. Rooms.find({}).fetch().forEach(function (room) {
  365. var type = room.type;
  366. if (Playlists.find({type: type}).count() === 0) {
  367. Playlists.insert({type: type, songs: []});
  368. }
  369. if (Playlists.findOne({type: type}).songs.length === 0) {
  370. Playlists.update({type: type}, {$push: {songs: default_song.mid}}, function() {
  371. stations.push(new Station(type));
  372. });
  373. } else {
  374. stations.push(new Station(type));
  375. }
  376. });
  377. Accounts.validateNewUser(function (user) {
  378. var username;
  379. if (user.services) {
  380. if (user.services.github) {
  381. username = user.services.github.username;
  382. } else if (user.services.facebook) {
  383. username = user.services.facebook.first_name;
  384. } else if (user.services.password) {
  385. username = user.username;
  386. }
  387. }
  388. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() !== 0) {
  389. throw new Meteor.Error(403, "An account with that username already exists.");
  390. } else {
  391. return true;
  392. }
  393. });
  394. Accounts.onCreateUser(function (options, user) {
  395. var username;
  396. if (user.services) {
  397. if (user.services.github) {
  398. username = user.services.github.username;
  399. } else if (user.services.facebook) {
  400. username = user.services.facebook.first_name;
  401. } else if (user.services.password) {
  402. username = user.username;
  403. }
  404. }
  405. user.profile = {
  406. username: username,
  407. usernameL: username.toLowerCase(),
  408. rank: "default",
  409. liked: [],
  410. disliked: [],
  411. settings: {showRating: false},
  412. realname: ""
  413. };
  414. return user;
  415. });
  416. Meteor.publish("alerts", function () {
  417. return Alerts.find({active: true})
  418. });
  419. Meteor.publish("allAlerts", function () {
  420. return Alerts.find({})
  421. });
  422. Meteor.publish("news", function () {
  423. return News.find({})
  424. });
  425. Meteor.publish("userData", function (userId) {
  426. if (userId !== undefined) {
  427. return Meteor.users.find(userId, {fields: {"services.github.username": 1, "punishments": 1}})
  428. } else {
  429. return undefined;
  430. }
  431. });
  432. Meteor.publish("allAlerts", function () {
  433. return Alerts.find({active: false})
  434. });
  435. Meteor.publish("playlists", function () {
  436. return Playlists.find({})
  437. });
  438. Meteor.publish("rooms", function () {
  439. return Rooms.find({});
  440. });
  441. Meteor.publish("songs", function () {
  442. return Songs.find({});
  443. });
  444. Meteor.publish("queues", function () {
  445. return Queues.find({});
  446. });
  447. Meteor.publish("reports", function () {
  448. return Reports.find({});
  449. });
  450. Meteor.publish("chat", function () {
  451. return Chat.find({});
  452. });
  453. Meteor.publish("userProfiles", function (username) {
  454. var settings = Meteor.users.findOne({"profile.usernameL": username}, {fields: {"profile.settings": 1}});
  455. if (settings !== undefined && settings.profile.settings) {
  456. settings = settings.profile.settings;
  457. if (settings.showRating === true) {
  458. return Meteor.users.find({"profile.usernameL": username}, {
  459. fields: {
  460. "profile.username": 1,
  461. "profile.usernameL": 1,
  462. "profile.rank": 1,
  463. createdAt: 1,
  464. "profile.liked": 1,
  465. "profile.disliked": 1,
  466. "profile.settings": 1,
  467. "profile.realname": 1
  468. }
  469. });
  470. }
  471. }
  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.settings": 1,
  479. "profile.realname": 1
  480. }
  481. });
  482. });
  483. Meteor.publish("isAdmin", function () {
  484. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  485. });
  486. Meteor.publish("isModerator", function () {
  487. return Meteor.users.find({_id: this.userId, "profile.rank": "moderator"});
  488. });
  489. Meteor.publish("feedback", function(){
  490. return Feedback.find();
  491. })
  492. function isAdmin() {
  493. var userData = Meteor.users.find(Meteor.userId());
  494. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  495. return true;
  496. } else {
  497. return false;
  498. }
  499. }
  500. function isModerator() {
  501. var userData = Meteor.users.find(Meteor.userId());
  502. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  503. return true;
  504. } else {
  505. return isAdmin();
  506. }
  507. }
  508. function isBanned() {
  509. var userData = Meteor.users.findOne(Meteor.userId());
  510. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  511. var ban = userData.punishments.ban;
  512. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  513. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  514. return false;
  515. } else {
  516. return true;
  517. }
  518. } else {
  519. return false;
  520. }
  521. }
  522. function isMuted() {
  523. var userData = Meteor.users.findOne(Meteor.userId());
  524. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.mute !== undefined) {
  525. var mute = userData.punishments.mute;
  526. if (new Date(mute.bannedUntil).getTime() <= new Date().getTime()) {
  527. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.mute": ""}});
  528. return false;
  529. } else {
  530. return true;
  531. }
  532. } else {
  533. return false;
  534. }
  535. }
  536. Meteor.methods({
  537. activateAlert: function(id) {
  538. if (isAdmin() && !isBanned()) {
  539. Alerts.update(id, {$set: {active: true}});
  540. } else {
  541. throw new Meteor.Error(403, "Invalid permissions.");
  542. }
  543. },
  544. deactivateAlert: function(id) {
  545. if (isAdmin() && !isBanned()) {
  546. Alerts.update(id, {$set: {active: false}});
  547. } else {
  548. throw new Meteor.Error(403, "Invalid permissions.");
  549. }
  550. },
  551. deleteAlert: function(id) {
  552. if (isAdmin() && !isBanned()) {
  553. Alerts.remove(id);
  554. } else {
  555. throw new Meteor.Error(403, "Invalid permissions.");
  556. }
  557. },
  558. fetchSong: function(type) {
  559. if (isAdmin() && !isBanned()) {
  560. getStation(type, function (station) {
  561. station.fetchSongs();
  562. });
  563. } else {
  564. throw new Meteor.Error(403, "Invalid permissions.");
  565. }
  566. },
  567. removeSongs: function(type) {
  568. if (isAdmin() && !isBanned()) {
  569. getStation(type, function (station) {
  570. station.removeSongs();
  571. });
  572. } else {
  573. throw new Meteor.Error(403, "Invalid permissions.");
  574. }
  575. },
  576. lockRoom: function (type) {
  577. if (isAdmin() && !isBanned()) {
  578. getStation(type, function (station) {
  579. station.lock();
  580. });
  581. } else {
  582. throw new Meteor.Error(403, "Invalid permissions.");
  583. }
  584. },
  585. unlockRoom: function (type) {
  586. if (isAdmin() && !isBanned()) {
  587. getStation(type, function (station) {
  588. station.unlock();
  589. });
  590. } else {
  591. throw new Meteor.Error(403, "Invalid permissions.");
  592. }
  593. },
  594. banUser: function (username, period, reason) {
  595. if (isAdmin() && !isBanned()) {
  596. var user = Meteor.user();
  597. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  598. var bannedUntil = (new Date).getTime() + (period * 1000);
  599. if (bannedUntil > 8640000000000000) {
  600. bannedUntil = 8640000000000000;
  601. }
  602. bannedUntil = new Date(bannedUntil);
  603. var banObject = {
  604. bannedBy: user.profile.usernameL,
  605. bannedAt: new Date(Date.now()),
  606. bannedReason: reason,
  607. bannedUntil: bannedUntil
  608. };
  609. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  610. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  611. } else {
  612. throw new Meteor.Error(403, "Invalid permissions.");
  613. }
  614. },
  615. muteUser: function (username, period) {
  616. if (isAdmin() && !isBanned()) {
  617. var user = Meteor.user();
  618. var mutedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  619. if (period === undefined || Number(period) === 0) {
  620. mutedUntil = 8640000000000000;
  621. } else {
  622. var mutedUntil = (new Date).getTime() + (period * 1000);
  623. if (mutedUntil > 8640000000000000) {
  624. mutedUntil = 8640000000000000;
  625. }
  626. }
  627. mutedUntil = new Date(mutedUntil);
  628. var muteObject = {mutedBy: user.profile.usernameL, mutedAt: new Date(Date.now()), mutedUntil: mutedUntil};
  629. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$set: {"punishments.mute": muteObject}});
  630. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$push: {"punishments.mutes": muteObject}});
  631. } else {
  632. throw new Meteor.Error(403, "Invalid permissions.");
  633. }
  634. },
  635. unbanUser: function (username) {
  636. if (isAdmin() && !isBanned()) {
  637. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.ban"});
  638. } else {
  639. throw new Meteor.Error(403, "Invalid permissions.");
  640. }
  641. },
  642. unsilenceUser: function (username) {
  643. if (isAdmin() && !isBanned()) {
  644. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.mute"});
  645. } else {
  646. throw new Meteor.Error(403, "Invalid permissions.");
  647. }
  648. },
  649. isBanned: function () {
  650. return isBanned();
  651. },
  652. isMuted: function () {
  653. return isMuted();
  654. },
  655. updateSettings: function (showRating) {
  656. if (Meteor.userId() && !isBanned()) {
  657. var user = Meteor.user();
  658. if (showRating !== true && showRating !== false) {
  659. showRating = false;
  660. }
  661. if (user.profile.settings) {
  662. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  663. } else {
  664. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  665. }
  666. } else {
  667. throw new Meteor.Error(403, "Invalid permissions.");
  668. }
  669. },
  670. resetRating: function () {
  671. if (isAdmin() && !isBanned()) {
  672. stations.forEach(function (station) {
  673. var type = station.type;
  674. var temp_songs = Playlists.findOne({type: type}).songs;
  675. Playlists.update({type: type}, {$set: {"songs": []}});
  676. temp_songs.forEach(function (song) {
  677. song.likes = 0;
  678. song.dislikes = 0;
  679. Playlists.update({type: type}, {$push: {"songs": song}});
  680. });
  681. });
  682. Meteor.users.update({}, {$set: {"profile.liked": [], "profile.disliked": []}}, {multi: true});
  683. } else {
  684. throw 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. });
  1199. Meteor.setInterval(function () {
  1200. checkUsersPR();
  1201. }, 10000);
  1202. Meteor.users.after.insert(function (err, user) {
  1203. Accounts.sendVerificationEmail(user._id);
  1204. });