server.js 43 KB

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