server.js 43 KB

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