2
0

server.js 44 KB

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