server.js 44 KB

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