server.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. }}, function(err) {
  986. console.log(err);
  987. if (err) {
  988. throw err.sanitizedError;
  989. } else {
  990. return true;
  991. }
  992. });
  993. return true;
  994. } else {
  995. throw new Meteor.Error(403, "Invalid permissions.");
  996. }
  997. },
  998. removeSongFromQueue: function (mid) {
  999. if (isModerator() && !isBanned()) {
  1000. Queues.remove({mid: mid});
  1001. } else {
  1002. throw new Meteor.Error(403, "Invalid permissions.");
  1003. }
  1004. },
  1005. removeSongFromPlaylist: function (type, mid) {
  1006. if (isModerator() && !isBanned()) {
  1007. Playlists.remove({type: type}, {$pull: {songs: mid}});
  1008. } else {
  1009. throw new Meteor.Error(403, "Invalid permissions.");
  1010. }
  1011. },
  1012. addSongToPlaylist: function (songData) {
  1013. if (isModerator() && !isBanned()) {
  1014. var requiredProperties = ["_id", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes", "requestedBy", "genres"];
  1015. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  1016. for (var property in requiredProperties) {
  1017. if (songData[requiredProperties[property]] === undefined) {
  1018. throw new Meteor.Error(403, "Invalid data.");
  1019. }
  1020. }
  1021. delete songData._id;
  1022. songData.approvedBy = Meteor.userId();
  1023. Songs.insert(songData);
  1024. Queues.remove({mid: songData.mid});
  1025. songData.genres.forEach(function(genre) {
  1026. genre = genre.toLowerCase();
  1027. if (Playlists.findOne({type: genre}) === undefined) {
  1028. Playlists.insert({type: genre, songs: [songData.mid]});
  1029. } else {
  1030. Playlists.update({type: genre}, {$push: {songs: songData.mid}});
  1031. }
  1032. });
  1033. return true;
  1034. } else {
  1035. throw new Meteor.Error(403, "Invalid data.");
  1036. }
  1037. } else {
  1038. throw new Meteor.Error(403, "Invalid permissions.");
  1039. }
  1040. },
  1041. createRoom: function (display, tag, private, desc) {
  1042. if (isAdmin() && !isBanned()) {
  1043. createRoom(display, tag, private, desc);
  1044. } else {
  1045. throw new Meteor.Error(403, "Invalid permissions.");
  1046. }
  1047. },
  1048. deleteRoom: function (type) {
  1049. if (isAdmin() && !isBanned()) {
  1050. Rooms.remove({type: type});
  1051. return true;
  1052. } else {
  1053. throw new Meteor.Error(403, "Invalid permissions.");
  1054. }
  1055. },
  1056. getUserNum: function () {
  1057. if (!isBanned()) {
  1058. return Object.keys(Meteor.default_server.sessions).length;
  1059. }
  1060. },
  1061. getTotalUsers: function () {
  1062. return Meteor.users.find().count();
  1063. },
  1064. updateRealName: function (realname) {
  1065. if (Meteor.userId()) {
  1066. var oldName = Meteor.users.findOne(Meteor.userId()).profile.realname;
  1067. Meteor.users.update(Meteor.userId(), {
  1068. $set: {"profile.realname": realname},
  1069. $push: {"profile.realnames": oldName}
  1070. });
  1071. } else {
  1072. throw new Meteor.Error(403, "Invalid permissions.");
  1073. }
  1074. },
  1075. updateUserName: function (newUserName) {
  1076. if (Meteor.userId()) {
  1077. var oldUsername = Meteor.users.findOne(Meteor.userId()).profile.username;
  1078. Meteor.users.update(Meteor.userId(), {
  1079. $set: {
  1080. "username": newUserName,
  1081. "profile.username": newUserName,
  1082. "profile.usernameL": newUserName.toLowerCase()
  1083. }, $push: {"profile.usernames": oldUsername}
  1084. });
  1085. } else {
  1086. throw new Meteor.Error(403, "Invalid permissions.");
  1087. }
  1088. },
  1089. /*updateUserRank: function(newRank){
  1090. if (Meteor.userId()) {
  1091. Meteor.users.update(Meteor.userId(), {$set: {"profile.rank": newRank}});
  1092. } else {
  1093. throw new Meteor.Error(403, "Invalid permissions.");
  1094. }
  1095. },*/
  1096. deleteAccount: function () {
  1097. if (Meteor.userId()) {
  1098. var user = Meteor.users.findOne(Meteor.userId());
  1099. Meteor.users.remove({_id: Meteor.userId()});
  1100. } else {
  1101. throw new Meteor.Error(403, "Invalid permissions.");
  1102. }
  1103. },
  1104. sendFeedback: function(message){
  1105. if(Meteor.userId() && !isBanned()) {
  1106. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1107. if (res.content.indexOf("true") > -1) {
  1108. return true;
  1109. } else {
  1110. Feedback.insert({
  1111. "username": Meteor.user().profile.username,
  1112. "message": message,
  1113. upvotes: 0,
  1114. upvotedBy: []
  1115. })
  1116. }
  1117. });
  1118. }
  1119. },
  1120. upvoteFeedback: function(message){
  1121. if(Meteor.userId() && !isBanned()){
  1122. console.log(Feedback.findOne({"message": message}));
  1123. if(Feedback.findOne({"message": message}).upvotedBy.indexOf(Meteor.user().profile.username) === -1){
  1124. Feedback.update({"message": message}, {$inc: {"upvotes": 1}});
  1125. Feedback.update({"message": message}, {$push: {"upvotedBy": Meteor.user().profile.username}});
  1126. } else{
  1127. Feedback.update({"message": message}, {$inc: {"upvotes": -1}});
  1128. Feedback.update({"message": message}, {$pull: {"upvotedBy": Meteor.user().profile.username}});
  1129. }
  1130. }
  1131. },
  1132. deleteFeedback: function(message){
  1133. if(isAdmin() && !isBanned()){
  1134. Feedback.remove({"message": message});
  1135. } else {
  1136. throw new Meteor.Error(403, "Invalid permissions.");
  1137. }
  1138. },
  1139. updateFeedback: function(oldMessage, newMessage){
  1140. if(isAdmin() && !isBanned()){
  1141. Feedback.update({"message": oldMessage}, {$set: {"message": newMessage}});
  1142. } else {
  1143. throw new Meteor.Error(403, "Invalid permissions.");
  1144. }
  1145. },
  1146. editRoomDesc: function(type, description){
  1147. if(isAdmin() && !isBanned()){
  1148. Rooms.update({type: type}, {$set: {"roomDesc": description}});
  1149. } else {
  1150. throw new Meteor.Error(403, "Invalid permissions.");
  1151. }
  1152. }
  1153. });
  1154. Meteor.setInterval(function () {
  1155. checkUsersPR();
  1156. }, 10000);
  1157. Meteor.users.after.insert(function (err, user) {
  1158. Accounts.sendVerificationEmail(user._id);
  1159. });