server.js 44 KB

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